Sub sequence occurrence in a string

后端 未结 4 1706
面向向阳花
面向向阳花 2021-01-02 21:23

Given 2 strings like bangalore and blr, return whether one appears as a subsequence of the other. The above case returns true whereas bangalore and brl returns false.

4条回答
  •  走了就别回头了
    2021-01-02 21:40

    Greedy strategy should work for this problem.

    • Find the first letter of the suspected substring (blr) in the big string (*b*angalore)
    • Find the second letter starting at the index of the first letter plus one (anga*l*ore)
    • Find the third letter starting at the index of the second letter plus one (o*r*e)
    • Continue until you can no longer find the next letter of blr in the string (no match), or you run out of letters in the subsequence (you have a match).

    Here is a sample code in C++:

    #include 
    #include 
    using namespace std;
    
    int main() {
        string txt = "quick brown fox jumps over the lazy dog";
        string s = "brownfoxzdog";
        int pos = -1;
        bool ok = true;
        for (int i = 0 ; ok && i != s.size() ; i++) {
            ok = (pos = txt.find(s[i], pos+1)) != string::npos;
        }
        cerr << (ok ? "Found" : "Not found") << endl;
        return 0;
    }
    

提交回复
热议问题