Sub sequence occurrence in a string

后端 未结 4 1707
面向向阳花
面向向阳花 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:25

    Find the length of the longest common subsequence. If it is equal to the length of small string, return true

    0 讨论(0)
  • 2021-01-02 21:27
    // Solution 1
    public static boolean isSubSequence(String str1, String str2) {
         int i = 0;
            int j = 0;
            while (i < str1.length() && j < str2.length()) {
                if (str1.charAt(i) == str2.charAt(j)) {
                    i++;
                    j++;
                } else {
                    i++;
                }
            }
        return j == str2.length();
    }
    
    // Solution 2 using String indexOf method
    public static boolean isSubSequenceUsingIndexOf(String mainStr, String subStr) {
        int i = 0;
        int index = 0;
        while(i<subStr.length()) {
            char c = subStr.charAt(i);
            if((index = mainStr.indexOf(c, index)) == -1) {
                return false;
            }
            i++;
        }
    
        return true;
    }
    
    0 讨论(0)
  • 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 <iostream>
    #include <string>
    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;
    }
    
    0 讨论(0)
  • 2021-01-02 21:47

    O(N) solution, where N is the length of the substring.

    bool subsequence( string s1, string s2 ){
        int n1 = s1.length();
        int n2 = s2.length();
    
        if( n1 > n2 ){
            return false;
        }
    
        int i = 0;
        int j = 0;
        while( i < n1 && j < n2 ){
            if( s1[i] == s2[j] ){
                i++;
            } 
            j++;
        }
    
        return i == n1;
    }
    
    0 讨论(0)
提交回复
热议问题