Implement strStr()

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

C++:
01 class Solution {
02 public:
03     char *strStr(char *haystack, char *needle) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         if((needle==NULL)||(*needle==))
07             return haystack;
08         vector<int> A;
09         int k=0;
10         A.push_back(0);
11         char* p=needle+1;
12         while(*p!=)
13         {
14             while((k>0)&&(*(needle+k)!=*p))
15             {
16                 k=A[k1];
17             }
18             if(*(needle+k)==*p)
19             {
20                 k++;
21             }
22             A.push_back(k);
23             p++;
24         }
25         int n=A.size();
26         k=0;
27         p=haystack;
28         while(*p!=)
29         {
30             while((k>0)&&(*(needle+k)!=*p))
31             {
32                 k=A[k1];
33             }
34             if(*(needle+k)==*p)
35             {
36                 k++;
37             }
38             if(k==n)
39             {
40                 return pk+1;
41             }
42             p++;
43         }
44         return NULL;
45     }
46 };
Advertisements
This entry was posted in Backtrack, String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s