原题地址:https://leetcode-cn.com/problems/is-subsequence/
题目描述:
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = "abc", t = "ahbgdc"
返回 true.
示例 2:
s = "axc", t = "ahbgdc"
返回 false.
解题方案:
查找子序列,因为字符串t很长,所以如果按照传统的判断方法时间复杂度不好,由于是有序的,所以从在主串查找到第一个字符的下一个位置开始查找。
代码:
class Solution {
public:
bool isSubsequence(string s, string t) {
int len = s.length();
if(len == 0)
return true;
int i = 0;
int pos = t.find(s[i], pos);
while(i < len)
{
if(pos != string :: npos)
i ++;
else
break;
pos = t.find(s[i], pos + 1);
}
if(i == len)
return true;
else
return false;
}
};