Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
给定两个字符串,求出将字符串1变为字符串2的最小操作步骤。
操作分三种:a)插入一个字符
b)删除一个字符
c)替换一个字符
这是一个很好的度量字符串之间相似程度的一个方式。
很明显是需要利用动态规划来求解的,做了很久终于做出来了。
即 pos[i][j] = min( pos[i - 1][j] + 1, pos[i][j - 1] + 1 ,pos[i - 1][j - 1] + word1.charAt(i) == word2.charAt(j))
public class Solution { public int minDistance(String word1, String word2) { int len1 = word1.length(); int len2 = word2.length(); int[][] pos = new int[len1+1][len2+1]; for (int i = 0; i <= len2; i++) pos[0][i] = i ; for (int i = 0; i <= len1; i++) pos[i][0] = i ; for (int i = 1; i <= len1 ; i++) { for (int j = 1; j<= len2 ; j++) { if( word1.charAt(i-1) == word2.charAt(j-1)) pos[i][j] = Math.min(Math.min(pos[i - 1][j] + 1, pos[i][j - 1] + 1),pos[i - 1][j - 1]); else pos[i][j] = Math.min(Math.min(pos[i - 1][j] + 1, pos[i][j - 1] + 1),pos[i - 1][j - 1]+1); } } return pos[len1][len2]; } }
其实还可以优化,优化成dp[len1]这样的结果,没有接着往下做,但是确实是可以接着做的。时间应该会更快。