您的位置:首页 > 其它

leetcode -- Implement strStr()

2014-08-15 12:25 288 查看

反正总是有人要赢,那为什么不能是我呢~

[问题描述]

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.暴力

char *Solution::strStr(char* haystack, char* needle)
{
if (haystack == NULL || needle == NULL)
return NULL;
if (needle[0] == '\0')
return haystack;
int next[strlen(needle)];//计算nextval
int i = 0, j = -1;
next[i] = -1;
while (needle[i] != '\0'){
if (j == -1 || needle[i] == needle[j]){
i++, j++; next[i] = j;
}
else{
j = next[j];
}
}
i = 0, j = 0;//匹配字符串
char* ans = NULL;
while (haystack[i] != '\0'){
while (j >= 0 && haystack[i] != needle[j])
j = next[j];
i++; j++;
if (needle[j] == '\0'){
ans = haystack + i - j;
return ans;
}
}
return ans;
}


暴力有效的方法1:

char *strStr(char *haystack, char *needle)
{
if(needle == NULL) return haystack;
else{
int len1 =strlen(haystack),len2 = strlen(needle);
if(len2 == 0) return haystack;
for(int i = 0 ; i < len1-len2+1; ++ i){
if(strncmp(haystack+i,needle,len2) == 0) return haystack+i;
}
return NULL;
}
}


暴力有效的方法2:

char *strStr(char *haystack, char *needle)
{
int i,j;
for (i = j = 0; haystack[i] && needle[j];) {
if (haystack[i] == needle[j]) {
++i;
++j;
} else {
i = i - j + 1;
j = 0;
}
}
return needle[j] ? 0 : (haystack + i - j);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: