1096: 字符串的修改

来源:互联网 发布:编程模拟蚂蚁寻找甜品 编辑:程序博客网 时间:2024/05/22 16:50

题目

Description

设A和B是两个字符串。我们要用最少的字符操作次数,将字符串A转换为字符串B。这里所说的字符操作共有三种:

  1. 删除一个字符;
  2. 插入一个字符;
  3. 将一个字符改为另一个字符。
    对任给的两个字符串A和B,计算出将字符串A变换为字符串B所用的最少字符操作次数。

Input

第一行为字符串A;第二行为字符串B;字符串A和B的长度均小于200。

Output

只有一个正整数,为最少字符操作次数。

Sample Input

sfdxbqw
gfdgw

Sample Output

4


代码块

//此题我用到了动态规划的思想。

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner cn = new Scanner(System.in);        String strA = cn.nextLine();        String strB = cn.nextLine();        System.out.println(getDistance(strA,strB));        cn.close();    }    public static int getDistance(String strA, String strB){        if (strA.equals(strB)) {//若两个字符串相同,返回0            return 0;        }        int lengthA=strA.length();        int lengthB=strB.length();        int length=Math.max(lengthA,lengthB);//找到两个字符串长度最大值定义,二维数组的长度        int array[][]=new int[length+1][length+1];//申请一个二维数组,存储转移矩阵        for(int i=0;i<=length;i++){//边界条件初始化            array[i][0]=i;        }        for(int j=0;j<=length;j++){            array[0][j]=j;        }        for(int i=1;i<=lengthA;i++){//状态转移方程            for(int j=1;j<=lengthB;j++){                array[i][j]=min(array[i-1][j]+1,                                array[i][j-1]+1,                                array[i-1][j-1]+(strA.charAt(i-1)==strB.charAt(j-1)?0:1));            }        }        return array[lengthA][lengthB];    }   //取三个数中的最小值    public static int  min(int a,int b, int c){        return Math.min(Math.min(a,b),c);    }}
1 0