问题
给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
例子
思路
-
方法1
动态规划
-
方法2
代码
//方法1
class Solution {
public int minDistance(String word1, String word2) {
int m=word1.length(),n=word2.length();
int[][] res = new int[m+1][n+1];
int max=0;
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++) {
if(word1.charAt(i-1)==word2.charAt(j-1)){
res[i][j]=res[i-1][j-1]+1;
}else{
res[i][j]=Math.max(res[i-1][j], res[i][j-1]);
}
if(res[i][j]>max) {
max=res[i][j];
}
}
}
return m+n-2*max;
}
}
//方法2