LeetCode动态规划系列 编辑距离 冲冲冲
作者:互联网
温故而知新嘛!
其实讲道理,这个编辑距离其实蛮简单的啊!
class Solution {
public int minDistance(String word1, String word2) {
int N = word1.length();
int M = word2.length();
if(N==0)
return M;
if(M==0)
return N;
int dp[][] = new int[N+1][M+1];
dp[0][0] = word1.charAt(0) == word2.charAt(0) ? 0 : 1;
//标记是否已经有相同的值了
boolean flag1 = false;
boolean flag2 = false;
if(word1.charAt(0)==word2.charAt(0)){
dp[0][0] = 0;
}
else{
dp[0][0] = 1;
}
for(int i = 1; i < M; i++){
//遇到不等的时候或已经有相同的值了
if(flag1 || word2.charAt(i) != word1.charAt(0)){
dp[0][i] = dp[0][i-1] + 1;
}
else{
dp[0][i] = dp[0][i-1];
flag1 = true;
}
}
for(int i = 1; i < N; i++){
if(flag2 || word1.charAt(i) != word2.charAt(0)){
dp[i][0] = dp[i-1][0] + 1;
}
else{
dp[i][0] = dp[i-1][0];
flag2 = true;
}
}
for(int i = 1; i < N; i++){
for(int j = 1; j < M; j++){
if(word1.charAt(i) == word2.charAt(j)){
dp[i][j] = dp[i-1][j-1];
}
else{
dp[i][j] = Math.min(dp[i-1][j-1],Math.min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}
return dp[N-1][M-1];
}
}
标签:charAt,冲冲,int,else,word1,word2,动态,LeetCode,dp 来源: https://blog.csdn.net/q1072118803/article/details/113729885