标签:style blog color io strong for ar art
[问题描述]
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
[解题思路]
1.KMP. 2.暴力
1 char *Solution::strStr(char* haystack, char* needle) 2 { 3 if (haystack == NULL || needle == NULL) 4 return NULL; 5 if (needle[0] == ‘\0‘) 6 return haystack; 7 int next[strlen(needle)];//计算nextval 8 int i = 0, j = -1; 9 next[i] = -1; 10 while (needle[i] != ‘\0‘){ 11 if (j == -1 || needle[i] == needle[j]){ 12 i++, j++; next[i] = j; 13 } 14 else{ 15 j = next[j]; 16 } 17 } 18 i = 0, j = 0;//匹配字符串 19 char* ans = NULL; 20 while (haystack[i] != ‘\0‘){ 21 while (j >= 0 && haystack[i] != needle[j]) 22 j = next[j]; 23 i++; j++; 24 if (needle[j] == ‘\0‘){ 25 ans = haystack + i - j; 26 return ans; 27 } 28 } 29 return ans; 30 }
暴力有效的方法1:
1 char *strStr(char *haystack, char *needle) 2 { 3 if(needle == NULL) return haystack; 4 else{ 5 int len1 =strlen(haystack),len2 = strlen(needle); 6 if(len2 == 0) return haystack; 7 for(int i = 0 ; i < len1-len2+1; ++ i){ 8 if(strncmp(haystack+i,needle,len2) == 0) return haystack+i; 9 } 10 return NULL; 11 } 12 }
暴力有效的方法2:
1 char *strStr(char *haystack, char *needle) 2 { 3 int i,j; 4 for (i = j = 0; haystack[i] && needle[j];) { 5 if (haystack[i] == needle[j]) { 6 ++i; 7 ++j; 8 } else { 9 i = i - j + 1; 10 j = 0; 11 } 12 } 13 return needle[j] ? 0 : (haystack + i - j); 14 }
leetcode -- Implement strStr(),布布扣,bubuko.com
leetcode -- Implement strStr()
标签:style blog color io strong for ar art
原文地址:http://www.cnblogs.com/taizy/p/3914581.html