思路 1 : 双指针
判断子序列是模板问题,非常典型 & 常用
要判断 s 是否为 t 的子序列,就要在 t 中按顺序匹配到 s 中的所有字符。所以我们遍历 s 中所有字符,通过一个指针遍历 t 中字符,直到匹配。然后继续遍历 s 中下一个字符,以此类推。如果匹配过程中指针超过了 t 的长度,说明 s 不是 t 的子序列,直接返回 false 即可
class Solution {
public:
bool isSubsequence(string s, string t) {
// 判断 s 是否为 t 的子序列:要匹配到 s 中每一个字符
int n = t.size(), index = 0;
for(char c : s) {
while(index < n && t[index] != c) index++;
if(index >= n) return false;
// 此时匹配到了,c = t[index],下一次要从 index + 1 开始匹配
index++;
}
return true;
}
};
时间复杂度:O(n + m)