[Leetcode] Implement strStr ()

Source: Internet
Author: User

Question: Implement strStr (). returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack. anwser 1: O (n * m) [cpp] class Solution {public: char * strStr (char * haystack, char * needle) {// Start typing your C/C ++ solution below // do not write int main () function int haylen = strlen (haystack); int needlen = strlen (needle ); for (int I = 0; I <= haylen-need Len; I ++) {char * p = haystack + I; char * q = needle; while (* q! = '\ 0') {if (* p! = * Q) {break;} else {p ++; q ++ ;}} if (* q = '\ 0') {return haystack + I ;}} return NULL ;}; an%2: O (n + m) KMP [cpp] class Solution {public: char * strStr (char * haystack, char * needle) {// Start typing your C/C ++ solution below // do not write int main () function int haylen = strlen (haystack); int needlen = strlen (needle ); int * fail = new int [needlen]; memset (fail,-1, needlen * sizeof (int) ); // Strlen (fail) int I, j, k; for (I = 1; I <needlen; ++ I) {for (k = fail [I-1]; k> = 0 & needle [I]! = Needle [k + 1]; k = fail [k]); if (needle [k + 1] = needle [I]) fail [I] = k + 1;} I = j = 0; while (I

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.