392. Is Subsequence*
https://leetcode.com/problems/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.
Follow up:
If there are lots of incoming S
, say S1, S2, ... , Sk
where k >= 1B
, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
C++ 实现 1
将 t
中的每个相同字符的索引保存到依次保存到同一个 vector
中, 这样我们得到了 record
. 遍历 s
, 用 target
表示 s[i]
的前一个字符的索引, 然后判断当前访问的字符 s[i]
的索引 *it
是否出现在 target
之后, 这可以用 upper_bound
来查找. 这种做法可以用来解决 792. Number of Matching Subsequences
class Solution {
public:
bool isSubsequence(string s, string t) {
unordered_map<char, vector<int>> record;
for (int i = 0; i < t.size(); ++ i) record[t[i]].push_back(i);
int target = -1;
for (int i = 0; i < s.size(); ++ i) {
if (!record.count(s[i])) return false;
auto it = std::upper_bound(record[s[i]].begin(), record[s[i]].end(), target);
if (it == record[s[i]].end()) return false;
target = *it;
}
return true;
}
};
C++ 实现 2
顺序访问 s
和 t
.
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s.empty()) return true;
int k = 0;
for (int i = 0; i < t.size(); ++i)
if (t[i] == s[k])
k ++;
return k >= s.size();
}
};
C++ 实现 3
来自 LeetCode Submission.
class Solution {
public:
bool isSubsequence(string s, string t) {
size_t index = 0;
for (char c: s) {
index = t.find(c, index);
if (index == string::npos)
return false;
index++;
}
return true;
}
}