Sub sequence occurrence in a string

后端 未结 4 1708
面向向阳花
面向向阳花 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: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;
    }
    

提交回复
热议问题