1. 程式人生 > >Leetcode 392. Is Subsequence

Leetcode 392. 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 tt 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).

問題解析:

    利用貪心算數的策略,t為母序列,s為子序列,如果在t中找到了s的某個字元,就立馬檢測下一個,t也指向下一個字元。



code:

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int i=0,j=0,count=0;
        for(;i<s.size(),j<t.size();){
            if(s[i]==t[j]){
                i++;j++;
                count++;
            }
            else{
                j++;
            }
        }
        if(count==s.size())
        return true;
     return false;   
    }
};