day55
1、leetcode583 两个字符串的删除操作
-
动归五步法
- dp[i] [j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数。
- 递推公式
- word1[i-1] == word2[j-1]
- dp[i] [j] = dp[i-1] [j-1]
- word1[i-1] != word2[j-1]
- 删word1[i - 1],dp[i] [j] = dp[i-1] [j] + 1
- 删word2[j - 1],dp[i] [j] = dp[i] [j-1] + 1
- 同时删word1[i - 1]和word2[j - 1],操作的最少次数为dp[i - 1] [j - 1] + 2
- dp[i] [j] = min({dp[i - 1] [j - 1] + 2, dp[i - 1] [j] + 1, dp[i] [j - 1] + 1});
- word1[i-1] == word2[j-1]
- 初始化
- dp[i] [0]:word2为空字符串,以i-1为结尾的字符串word1要删除多少个元素,才能和word2相同
- dp[i] [0] = i
- dp[0] [j] = j
- dp[i] [0]:word2为空字符串,以i-1为结尾的字符串word1要删除多少个元素,才能和word2相同
- 遍历顺序
- 从上到下,从左到右
- 举例
-
代码
class Solution { public int minDistance(String word1, String word2) { int[][] dp = new int[word1.length()+1][word2.length()+1]; for(int i=0; i<=word1.length(); i++) { dp[i][0] = i; } for(int j=1; j<=word2.length(); j++) { dp[0][j] = j; } for(int i=1; i<=word1.length(); i++) { for(int j=1; j<=word2.length(); j++) { if(word1.charAt(i - 1) == word2.charAt(j-1)) { dp[i][j] = dp[i-1][j-1]; } else { dp[i][j] = Math.min(dp[i - 1][j - 1] + 2, Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1)); } } } return dp[word1.length()][word2.length()]; } }
2、leetcode72 编辑距离
-
动归五步法
- dp[i] [j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要操作的最少次数。
- 递推公式
- word1[i-1] == word2[j-1]
- dp[i] [j] = dp[i-1] [j-1]
- word1[i-1] != word2[j-1]
- 删除
- 删word1[i - 1],dp[i] [j] = dp[i-1] [j] + 1【相当于word2 添加一个字符】
- 删word2[j - 1],dp[i] [j] = dp[i] [j-1] + 1【相当于word1 添加一个字符】
- 插入
- 替换
word1替换word1[i - 1],使其与word2[j - 1]相同,此时不用增删加元素。 dp[i] [j] = dp[i - 1] [j - 1] + 1;
- 删除
- dp[i] [j] = min({dp[i - 1] [j - 1], dp[i - 1] [j], dp[i] [j - 1]}) + 1;
- word1[i-1] == word2[j-1]
- 初始化
- dp[i] [0]:word2为空字符串,以i-1为结尾的字符串word1要删除多少个元素,才能和word2相同
- dp[i] [0] = i
- dp[0] [j] = j
- dp[i] [0]:word2为空字符串,以i-1为结尾的字符串word1要删除多少个元素,才能和word2相同
- 遍历顺序
- 从上到下,从左到右
- 举例
-
代码
class Solution { public int minDistance(String word1, String word2) { int[][] dp = new int[word1.length()+1][word2.length()+1]; for(int i=0; i<=word1.length(); i++) { dp[i][0] = i; } for(int j=1; j<=word2.length(); j++) { dp[0][j] = j; } for(int i=1; i<=word1.length(); i++) { for(int j=1; j<=word2.length(); j++) { if(word1.charAt(i - 1) == word2.charAt(j-1)) { 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[word1.length()][word2.length()]; } }

浙公网安备 33010602011771号