这里运用了最小距离的算法 经典的动态规划
相同字符 左上角值加1 不相同字符 邻居三个取最小
注意点也要把"" 空字符串考虑进去
三个求最小可以改下为 Math.min(n, Math.min(m,l))
class Solution { public int min(int n , int m ,int l) { int temp = 0; if(m<=n&&m<=l) temp = m; else if(n<=m&&n<=l) temp = n; else if(l<=n&&l<=m) temp = l; return temp; } public int minDistance(String word1, String word2) { int n = word1.length(); int m = word2.length(); int arr[][] = new int [n+1][m+1]; //word1 变成 空所需要的删除的步骤 for (int i = 1; i <= n; i++) { arr[i][0] = i; } //空 变成 word2所需要的添加的步骤 for (int j = 1; j <= m; j++) { arr[0][j] = j; } for(int i = 1 ; i <= n ; i ++) { for(int j = 1 ; j <= m ; j++) { if(word2.charAt(j-1)==word1.charAt(i-1)) { arr[i][j] = arr[i-1][j-1]; } else { arr[i][j] = 1+ min(arr[i-1][j],arr[i][j-1],arr[i-1][j-1]); } } } return arr[n][m]; } }
更快一点的做法
class Solution { public int minDistance(String word1, String word2) { int m = word1.length(),n = word2.length(); if(m==0||n==0) return m==0?n:m; int[][] dp = new int[m+1][n+1]; //dp[i+1][j+1]表示word1的前i个字符和word2的前j个字符的编辑距离 for(int i = 0; i <= m; i++)dp[i][0] = i; for(int i = 0; i <= n; i++)dp[0][i] = i; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ int tmp = word1.charAt(i) == word2.charAt(j) ? 0 : 1; dp[i+1][j+1] = Math.min(Math.min(dp[i+1][j], dp[i][j+1])+1,dp[i][j]+tmp); } } return dp[m][n]; } }