标签:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
1 class Solution { 2 public: 3 int strStr(char *haystack, char *needle) { 4 5 int n1=strlen(haystack); 6 int n2=strlen(needle); 7 int result=-1; 8 bool flag; 9 for(int i=0;i<n1-n2+1;i++) 10 { 11 flag=true; 12 for(int j=0;j<n2;j++) 13 { 14 if(haystack[i+j]==needle[j]) 15 { 16 continue; 17 } 18 else 19 { 20 flag=false; 21 break; 22 } 23 } 24 25 if(flag==true) 26 { 27 result=i; 28 break; 29 } 30 } 31 return result; 32 } 33 };
a
|
b |
a
|
a
|
b
|
a
|
b
|
a
|
-1
|
0
|
0
|
1
|
1
|
2
|
3
|
2
|
1 class Solution { 2 public: 3 int strStr(char *haystack, char *needle) { 4 5 int i=0; 6 int j=0; 7 int n1=strlen(haystack); 8 int n2=strlen(needle); 9 10 vector<int> next=getNext(needle); 11 12 while(i<n1&&j<n2) 13 { 14 if(j==-1||haystack[i]==needle[j]) 15 { 16 i++; 17 j++; 18 } 19 else 20 { 21 j=next[j]; 22 } 23 } 24 25 if(j==n2) 26 { 27 return i-j; 28 } 29 else 30 { 31 return -1; 32 } 33 } 34 35 vector<int> getNext(char *needle) 36 { 37 int n=strlen(needle); 38 39 vector<int> next(n); 40 if(n==0) 41 { 42 return next; 43 } 44 45 next[0]=-1; 46 47 int i=0; 48 int k=-1; 49 while(i<n-1) 50 { 51 if(k==-1||needle[k]==needle[i]) 52 { 53 54 i++; 55 k++; 56 next[i]=k; 57 } 58 else 59 { 60 k=next[k]; 61 } 62 } 63 64 return next; 65 66 } 67 68 };
a
|
b |
a
|
a
|
b
|
a
|
b
|
a
|
-1
|
0
|
0
|
1
|
1
|
2
|
3
|
2
|
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4189219.html