[LeetCode]Implement strStr()
2015-02-05 10:10
369 查看
Q:Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题是让我们自己完善函数strStr():返回模式串needle在主串haystack中第一次出现的索引位置,若主串中不存在模式串,则返回-1。解法很容易想到,大二下学期数据结构关于字符串的一章,用KMP算法就可以解决。这里就不自己写KMP到底是怎么实现的了,给一个写的很棒的链接:从头到尾彻底理解KMP(2014年8月22日版)
代码贴上:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题是让我们自己完善函数strStr():返回模式串needle在主串haystack中第一次出现的索引位置,若主串中不存在模式串,则返回-1。解法很容易想到,大二下学期数据结构关于字符串的一章,用KMP算法就可以解决。这里就不自己写KMP到底是怎么实现的了,给一个写的很棒的链接:从头到尾彻底理解KMP(2014年8月22日版)
代码贴上:
class Solution { public: void getNextArray(char* needle, int next []){ int len = strlen(needle); int j = 0, k; next[j] = -1; k = next[j]; while (j != len){ if (needle[j] == needle[k] || k == -1){ j++; k++; next[j] = k; } else{ k = next[k]; } } } int strStr(char *haystack, char *needle) { int len1 = strlen(needle);//p int len2 = strlen(haystack);//q if (len1 > len2) return -1; int* next=new int[len1+1]; getNextArray(needle, next); int p = 0, q = 0; while (p < len1&&q < len2){ if (haystack[q] == needle[p]){ p++; q++; } else{ if (p == 0) q++; else p = next[p]; } } if (p < len1) return -1; return q - len1; } };
相关文章推荐
- leetcode 28 Implement strStr()
- leetcode(57)- Implement strStr()
- leetcode (28) - Implement strStr()
- LeetCode : Implement strStr() [java]
- LeetCode Implement strStr()
- [LeetCode] Implement strStr() 解题报告
- Leetcode: Implement strStr()
- LeetCode:Implement strStr()
- leetcode5 Implement strstr() 实现strstr函数功能
- 【LeetCode28】【 Implement strStr()】length,length(),size()
- LeetCode28 Implement strStr()
- Leetcode-Implement strStr()
- 【leetcode】Implement strStr()
- [LeetCode]Implement strStr()
- [leetcode-28]implement strstr()(C语言)
- [Leetcode][python]Implement strStr()/KMP算法
- LeetCode-028 Implement strStr()
- Leetcode-Implement strStr()
- [leetcode]Implement strStr()
- leetcode[28]Implement strStr()