题目地址:
https://leetcode.com/problems/delete-operation-for-two-strings/
给定两个字符串 s 1 s_1 s1和 s 2 s_2 s2,每一步允许从其中任意一个字符串里删去一个字符。问至少删多少次可以使得两个字符串变得一样。
思路是动态规划。对于一个字符串来说,删掉其某个字符后得到的剩余串一定是原串的子序列,所以这道题相当于问两个串的最长公共子序列的长度是多少,可以参考https://blog.csdn.net/qq_46105170/article/details/103867442。代码如下:
public class Solution {
public int minDistance(String word1, String word2) {
int n1 = word1.length(), n2 = word2.length();
int[][] dp = new int[n1 + 1][n2 + 1];
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n2; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// 注意这里是问要删掉多少个字符
return n1 + n2 - 2 * dp[n1][n2];
}
}
时空复杂度 O ( n 1 n 2 ) O(n_1n_2) O(n1n2), n 1 n_1 n1和 n 2 n_2 n2分别是 s 1 s_1 s1和 s 2 s_2 s2的长度。