[Lintcode] String lookup

Source: Internet
Author: User
Tags lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.