题目描述
题意分析
给两个字符串s和t, 判断s是不是t的子序列(不连续)
follow-up, 如果s有很多个, 怎样处理?
算法分析
s和t都扫一遍就好了..
实现
class Solution {
public:
bool isSubsequence(string s, string t) {
int j = 0, i = 0, slen = s.size(), tlen = t.size();
while (i < tlen && j < slen)
if (t[i++] == s[j]) j++;
return (j > (slen-1));
}
};
关于follow-up
扫一遍t, 将各个字母出现过的位置先后存在一个查询表里面,以字母为索引,
对每个s, 扫一遍, 对每个字符在查询表中能否找到符合条件的最小位置, 此时由于查询表是有序的,所以可以用二分查找
例子如下
代码参考:(来自cdai )
public boolean isSubsequence(String s, String t) {
List<Integer>[] idx = new List[256]; // Just for clarity
for (int i = 0; i < t.length(); i++) {
if (idx[t.charAt(i)] == null)
idx[t.charAt(i)] = new ArrayList<>();
idx[t.charAt(i)].add(i);
}
int prev = 0;
for (int i = 0; i < s.length(); i++) {
if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE
int j = Collections.binarySearch(idx[s.charAt(i)], prev);
if (j < 0) j = -j - 1;
if (j == idx[s.charAt(i)].size()) return false;
prev = idx[s.charAt(i)].get(j) + 1;
}
return true;
}