2017算法课.09(Is Subsequence)

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.




当t中找到匹配的字符时,迭代t,s的先行指数。
只要它到达t的末尾,或者我们发现s中的所有字符,停止循环。
 循环后,如果s的指数等于其长度,则返回true。 否则返回false。

bool isSubsequence(string s, string t) {
    int sLength = s.length(), sIndex = 0, tLength = t.length();
    for (int i=0; i<tLength && sIndex<sLength; i++)
        if (t[i]==s[sIndex]) sIndex++;
    return sIndex==sLength;
}

猜你喜欢

转载自blog.csdn.net/newandbetter/article/details/70477828