Given two strings s
and t
, return true
if s
is a subsequence of t
, or false
otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
Input: s = "abc", t = "ahbgdc" Output: true
Example 2:
Input: s = "axc", t = "ahbgdc" Output: false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 104
s
andt
consist only of lowercase English letters.
Follow up: Suppose there are lots of incoming s
, say s1, s2, ..., sk
where k >= 109
, and you want to check one by one to see if t
has its subsequence. In this scenario, how would you change your code?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
/* Follow Up | |
- k is big | |
Time: O(k * len(s) * log len(t)) | |
Space: O(len(t) * len(t)) | |
*/ | |
bool isSubsequence(string s, string t) { | |
// preprocess: "abb" -> {a: [0], b: [1, 2]} | |
map<char, vector<int>> indexes; | |
for(int i = 0; i < t.size(); i++) | |
indexes[t[i]].push_back(i); | |
// check each s | |
int cur = -1; | |
for(auto c: s){ | |
// char not found in t | |
if(indexes.find(c) == indexes.end()) | |
return false; | |
// binary search | |
// find the first pos whose value is greater than prev | |
auto idx = indexes[c]; | |
auto it = upper_bound(idx.begin(), idx.end(), cur); | |
if(it == idx.end()) | |
return false; | |
cur = *it; | |
} | |
return true; | |
} | |
}; |
No comments:
Post a Comment