美文网首页
392. Is Subsequence 判断子序列

392. Is Subsequence 判断子序列

作者: 这就是一个随意的名字 | 来源:发表于2017-07-30 10:30 被阅读0次

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,判断s是否是t的子序列。
这里假定s和t都只含有小写字母,t可以是非常长的字符串(长度约为500,000),s是短字符串(长度小于100)。
注意子序列是由原生序列中的某些元素按照相对位置不变的状态组成的新序列。
进阶:若输入的待检测短序列s有很多个,而你又想一个一个检测是否为t的子序列,如何改写你的代码?


思路
简单的做法,t中依次对s的首个字母进行匹配,成功则匹配s的下一个字母,直到s被匹配完成(返回true)或t扫描结束且s仍未匹配完(返回false),这里注意,对于s为空的情况,总是匹配为true。

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.size()>t.size()) return false;
        if(s=="")   return true;
        for(auto sit=s.begin(),tit=t.begin(); tit!=t.end();tit++){
            if(*sit==*tit)  sit++;
            if(sit==s.end())    return true;
        }
        return false;
    }
};

相关文章

网友评论

      本文标题:392. Is Subsequence 判断子序列

      本文链接:https://www.haomeiwen.com/subject/dhphlxtx.html