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?
题目中问s是否是t的子序列,而且表示t会很长
思路:
- 简单粗暴的逐个字符比较,如果只有一个s一个t的比较还是可以的,对follow up的问题有很多s一个接一个地和t比较来说就比较慢了
i指向s,j指向 t
当结束时如果i指向s的末尾就表示s是t的子序列
//18ms
public boolean isSubsequence(String s, String t) {
if (s == null || t == null) {
return false;
}
int i = 0;
int j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
i ++;
j ++;
} else {
j ++;
}
}
if (i >= s.length()) {
return true;
}
return false;
}
代码精简后如下:
//13ms
public boolean isSubsequence(String s, String t) {
if (s == null || t == null) {
return false;
}
int i = 0;
int j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j++)) {
i ++;
}
}
return (i == s.length());
}
2.对follow up中很多s一个接一个和t比较的问题,要在t上作文章,
参照https://www.cnblogs.com/grandyang/p/5842033.html的方法2
字母就只有26个,而t很长,对应的位置会有很多个,所以用hashMap来保存每个字母对应的位置
*说到hashMap,又习惯性地想起了它和hashTable的区别,这里不需要考虑线程安全,就用hashMap
直接引用 “然后遍历字符串s中的每个字符,对于每个遍历到的字符c,我们到 HashMap 中的对应的字符数组中去搜索,由于位置数组是有序的,我们使用二分搜索来加快搜索速度,这里需要注意的是,由于子序列是有顺序要求的,所以需要一个变量 pre 来记录当前匹配到t字符串中的位置,对于当前s串中的字符c,即便在t串中存在,但是若其在位置 pre 之前,也是不能匹配的。”
但是这个方法cpp要跑100ms
//100ms
bool isSubsequence(string s, string t) {
int pre = -1;
unordered_map<char, vector<int>> pos;
for (int i = 0; i < t.size(); i++) {
pos[t[i]].push_back(i);
}
for (int i = 0; i < s.size(); i++) {
auto it = upper_bound(pos[s[i]].begin(), pos[s[i]].end(), pre);
if (it == pos[s[i]].end()) {
return false;
}
pre = *it;
}
return true;
}