LeetCode-392-判断子序列

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,”ace”是”abcde”的一个子序列,而”aec”不是)。

示例 1:

1
2
3
s = "abc", t = "ahbgdc"

返回 true.

示例 2:

1
2
3
s = "axc", t = "ahbgdc"

返回 false.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//时间复杂度O(N),N为子序列的长度
//空间复杂度O(N*M)),substr函数的空间复杂度
class Solution {
public:
bool isSubsequence(string s, string t) {
bool res=true;
int idx=0;

for(int i=0;i<s.size();i++){
idx = t.find(s[i]);
if(idx<0){
res=false;
return res;
}else{
//每次基于已找到的剩余子串开始找
t = t.substr(idx+1);
}
}
return res;
}
};

----\(˙<>˙)/----赞赏一下吧~