Brute Force solution (O (MN)):
1 classSolution {2 Public:3 /**4 * Returns A index to the first occurrence of target in source,5 * or-1 If Target is no part of source.6 * @param source string to is scanned.7 * @param target string containing the sequence of characters to match.8 */9 intSTRSTR (Const Char*source,Const Char*target) {Ten //Write your code here One if(!source | |!target)return-1; A intm = strlen (source), n =strlen (target); - for(inti =0; I < M-n +1; i++) { - intj =0, k =i; the for(; J < N; j + +, k++) - if(Source[k]! =Target[j]) - Break; - if(j = = N)returni; + } - return-1; + } A};
KMP (O (M + N)):
1 classSolution {2 Public:3 /**4 * Returns A index to the first occurrence of target in source,5 * or-1 If Target is no part of source.6 * @param source string to is scanned.7 * @param target string containing the sequence of characters to match.8 */9 intSTRSTR (Const Char*source,Const Char*target) {Ten //Write your code here One if(!source | |!target)return-1; A intm = strlen (source), n =strlen (target); - if(!n)return 0; -vector<int> lps =kmpprocess (target, n); the for(inti =0, j =0; I <m;) { - if(Source[i] = =Target[j]) { -i++; -J + +; + } - if(j = = N)returnIJ; + if(I < m && Source[i]! =Target[j]) { A if(j) J = lps[j-1]; at Elsei++; - } - } - return-1; - } - Private: invector<int> kmpprocess (Const Char* Target,intN) { -vector<int> LPs (N,0); to for(inti =1, Len =0; I <N;) { + if(Target[i] = =Target[len]) -lps[i++] = + +Len; the Else if(len) len = Lps[len-1]; * Elselps[i++] =0; $ }Panax Notoginseng returnLPs; - } the};
[Lintcode] String lookup