LeetCode Delete Operation for Two Strings

LeetCode Delete Operation for Two Strings

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

  1. The length of given words won't exceed 500.
  2. Characters in given words can only be lower-case letters.

给定两个字符串,求最少的删除次数,使得两个字符串相等。

这其实就是求两个字符串的最长公共子序列,因为最少的删除次数之后,两个字符串都变成了lcs,则每个字符串删除的次数就是原始长度减去lcs的长度。

代码如下:

class Solution {
private:
	int lcs(const string& s1, const string& s2) {
		int n1 = s1.size(), n2 = s2.size();
		vector<int> dp1(n2 + 1, 0), dp2(n2 + 1, 0);
		int ans = 0;
		for (int i = 1; i <= n1; ++i) {
			for (int j = 1; j <= n2; ++j) {
				if (s1[i - 1] == s2[j - 1])dp2[j] = dp1[j - 1] + 1;
				else dp2[j] = max(dp1[j], dp2[j - 1]);
				ans = max(ans, dp2[j]);
			}
			dp1.swap(dp2);
		}
		return ans;
	}

public:
	int minDistance(string word1, string word2) {
		int l = lcs(word1, word2);
		return word1.size() - l + word2.size() - l;
	}
};

本代码提交AC,用时52MS。

Leave a Reply

Your email address will not be published. Required fields are marked *