Week16
Problem–Medium–392. Is Subsequence
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
s = "abc"
, t = "ahbgdc"
Return true
.
Example 2:
s = "axc"
, t = "ahbgdc"
Return false
.
题目解析:
这道题目可以用动态规划算法进行求解,首先,我们需要将问题划分出其子问题,也就是前状态是什么,我们求解两段不同长度m,n字符串是否为子串关系,其前状态可以分为求解长度为m-1,n-1的字符串是否为子串关系。所以我们可以直观定义dp[i][j]为长度为i,j的字符串是否为子串关系,这个关系不是单纯的真假关系,而是两者最长的公共子字符串的长度,这样我们在最后只需判断dp[m][n]是否等于s的长度即可。优化后,状态数组可以变为一维数组。
定义状态:
dp[i][j]为长度为i的字符串s与长度为j的字符串t最长公共子字符串长度。
状态转移:
if (s[i – 1] == t[j – 1]): dp[i][j] = dp[i – 1][j – 1] + 1;
else: dp[i][j] = max(dp[i][j – 1], dp[i – 1][j])
优化后:
状态变量可变为dp[i],因为每次更新之后只会用到上一次更新的值,没必要保留所有i更新的值,所以我们保存一次更新值即可,在下次更新中用自己的旧值进行更新。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
vector<int> dp(t.length() + 1, 0);
for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= t.length(); j++) {
if (s[i - 1] == t[j - 1]) {
dp[j] = min(dp[j - 1] + 1, i);
//cout << s[i - 1] << " " << dp[j] << endl;
} else {
dp[j] = max(dp[j - 1], dp[j]);
}
//cout << dp[j] << endl;
}
}
if (dp[t.length()] == s.length()) {
return true;
} else {
return false;
}
}
};
简单方法:
其实这道题根本不需要用动态规划来做,LeetCode上分类是动态规划所以引导别人用动态规划做。最简单的方法其实只需遍历t字符串,遇到与s相同字符的s的指针前进一,最后判断s的指针是否直到字符串尾即可。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
int pos = 0;
for (int i = 0; i < t.length(); i++) {
if (t[i] == s[pos]) {
pos++;
}
}
return pos == s.length();
}
};