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 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.

Solution, brute force (TLE)

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int ns = s.size(), nt = t.size();
        if ( ns == 0 ) return true;
        if ( ns > nt ) return false;
        vector<vector<bool>> res(ns, vector<bool>(nt, false));
        if ( s[0] == t[0] ) res[0][0] = true;
        for ( int it = 1; it < nt; it++ ) {
            if ( s[0] == t[it] ) res[0][it] = true;
            else res[0][it] = res[0][it-1];
        }
        for ( int is = 1; is < ns; is++ ) {
            for ( int it = is; it < nt; it++ ) {
                if ( s[is] == t[it] and res[is-1][it-1] ) res[is][it] = true;
                else res[is][it] = res[is][it-1];
            }
        }
        return res[ns-1][nt-1];
    }
};
class Solution {
public:
    bool isSubsequence(string s, string t) {
        unordered_map<char, queue<int>> map;
        int ns = s.size(), nt = t.size();
        for ( int is = 0; is < ns; is++ ) map[s[is]].push(is);
        int last = -1;
        for ( int it = 0; it < nt; it++ ) {
            if ( map.find(t[it]) == map.end() ) continue;
            if ( map[t[it]].front() != last+1 ) continue;
            map[t[it]].pop();
            if ( map[t[it]].empty() ) map.erase(map.find(t[it]));
            last += 1;
        }
        return ( last == ns-1);
    }
};

results matching ""

    No results matching ""