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); }
相关文章推荐
- 【leetcode】3.2 Implement strStr()
- [LeetCode] 028. Implement strStr() (Easy) (C++/Python)
- LeetCode -- Implement strStr()
- leetcode-28-Implement strStr()
- LeetCode-Implement strStr()
- leetcode-28 Implement strStr()
- leetcode: Implement strStr()
- LeetCode (Implement strStr())
- LeetCode-Implement strStr()
- leetcode第15题----- Implement strStr()
- 【LeetCode】Implement strStr()
- [LeetCode 28] Implement strStr()
- Leetcode:Implement strStr()
- [Leetcode] Implement strStr()
- [Leetcode] Implement strStr()
- Leetcode-Implement strStr()
- [LeetCode28] Implement strStr()
- leetcode---Implement strStr()
- leetcode 28: Implement strStr() (KMP算法)
- leetcode Implement strStr()