Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub sequence occurrence in a string

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.

like image 725
princess of persia Avatar asked Dec 22 '11 04:12

princess of persia


2 Answers

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;
}
like image 94
Sergey Kalinichenko Avatar answered Oct 31 '22 01:10

Sergey Kalinichenko


// 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;
}
like image 38
Pani Dhakshnamurthy Avatar answered Oct 30 '22 23:10

Pani Dhakshnamurthy