Microsoft Interview Question

find the last substring occurrenance's first element: example string:"abcdefab" and substring:"ab" awnser should return 6

Interview Answer

Anonymous

Feb 6, 2013

int lastPattern(const string& str, const string& patt) { if (str.empty() || patt.empty() || patt.size() > str.size()) return -1; int index(-1); for (int i = 0; i < str.size(); ) { int j(0); for ( ; j < patt.size(); ++j) if (str[i+j] != patt[j]) // terminate on first non-matching char break; // this means we've matched the pattern -- update index if (j == patt.size()) index = i; // increment i i += j+1; } return index; }