这一类的题型有很多,但总的来说思路是一样的。我在这里先给出我们常见的求两个字符串的最长公共序列的,然后逐渐的介绍这道题的三种解法:
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
2021年6月23日对他的全新理解
动态规划:
public int minDistance(String word1, String word2) {
if(word1.length()==0 || word2.length()==0){
return Math.max(word1.length(),word2.length());
}
char[] array1=word1.toCharArray();
char[] array2=word2.toCharArray();
int len1=word1.length();
int len2=word2.length();
int[][] p=new int[len1][len2]; //从word1的前i个,变道word2的前j个需要的代价;
//初始化2
boolean tag=false;
for(int i=0;i<len1;i++){
if(array1[i]==array2[0] || tag){
p[i][0]=i;
tag=true;
}else{
p[i][0]=i+1;
}
}
tag=false;
for(int j=0;j<len2;j++){
if(array1[0]==array2[j] || tag){
p[0][j]=j;
tag=true;
}else{
p[0][j]=j+1;
}
}
//初始化另一种办法
/*p[0][0]= array1[0]==array2[0] ? 0:1;
for(int i=1;i<len1;i++){
p[i][0]= array1[i]==array2[0] ? i:p[i-1][0]+1;
}
for(int j=1;j<len2;j++){
p[0][j]= array1[0]==array2[j] ? j:p[0][j-1]+1;
}*/
//状态转化过程1
for(int i=1;i<len1;i++){
for(int j=1;j<len2;j++){
if(array1[i]==array2[j]){
p[i][j]=p[i-1][j-1];
}else{
p[i][j]=1+Math.min(p[i][j-1],Math.min(p[i-1][j-1],p[i-1][j]));//加一个,修改,去掉
}
}
}
return p[len1-1][len2-1];
}
其次就是进一步压缩空间的办法:
package leetcode;
//压缩空间,因为一直用的是这三个。