C++ 4 lines simple solution

  • 12

    Iterate t, advance index of s when we found a matched char in t.
    Stop the loop whenever it reaches the end of t or we found all characters in s.
    After the loop, return true if index of s is equal to its length. Otherwise, return false.

    bool isSubsequence(string s, string t) {
        int sLen = s.length(), sIdx = 0, tLen = t.length();
        for (int i=0; i<tLen && sIdx<sLen; i++) 
            if (t[i]==s[sIdx]) sIdx++;
        return sIdx==sLen;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.