Recursive Solution C++


  • 0
    A

    Basically, look for a first char of s in t, then continue by incrementing index of s, and only search t for next char after the index where the first one was found.

    bool isSubsequence(string s, string t) {
        return helper(s, 0, t, 0);
    }
    
    bool helper(const string& s, int index1, const string& t, int index2){
        if (index1 == s.length()) return true;
        if (index2 == t.length()) return false;
        auto occ = t.find(s[index1], index2);
        if (occ == string::npos) return false;
        return helper(s, index1 + 1, t, occ + 1);
    }

Log in to reply
 

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