【LeetCode】28. Implement strStr() (2 solutions)
2014-05-26 21:58
381 查看
Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:暴力解
![](http://images0.cnblogs.com/blog2015/458814/201507/261143077482483.jpg)
解法二:标准KMP算法。可参考下文。
KMP算法详解
(1)先对模式串needle做“自匹配”,即求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。
(2)依据next数组信息,进行haystack与needle的匹配。
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
解法一:暴力解
class Solution { public: int strStr(string haystack, string needle) { int m = haystack.size(); int n = needle.size(); for(int i = 0; i <= m-n; i ++) { int j; for(j = 0; j < n; j ++) { if(haystack[i+j] != needle[j]) break; } if(j == n) return i; } return -1; } };
![](http://images0.cnblogs.com/blog2015/458814/201507/261143077482483.jpg)
解法二:标准KMP算法。可参考下文。
KMP算法详解
(1)先对模式串needle做“自匹配”,即求出模式串前缀与后缀中重复部分,将重复信息保存在next数组中。
(2)依据next数组信息,进行haystack与needle的匹配。
class Solution { public: int strStr(char *haystack, char *needle) { int hlen = strlen(haystack); int nlen = strlen(needle); int* next = new int[nlen]; getNext(needle, next); int i = 0; int j = 0; while(i < hlen && j < nlen) { if(j == -1 || haystack[i] == needle[j]) {// match current position, go next i ++; j ++; } else {// jump to the previous position to try matching j = next[j]; } } if(j == nlen) // all match return i-nlen; else return -1; } void getNext(char *needle, int next[]) {// self match to contruct next array int nlen = strlen(needle); int j = -1; // slow pointer int i = 0; // fast pointer next[i] = -1; //init next has one element while(i < nlen-1) { if(j == -1 || needle[i] == needle[j]) { j ++; i ++; //thus the condition (i < nlen-1) next[i] = j; //if position i not match, jump to position j } else { j = next[j]; //jump to the previous position to try matching } } } };
![](http://images.cnitblog.com/i/458814/201405/262157521199028.jpg)
相关文章推荐
- leetcode --28. Implement strStr()
- leetcode 28. Implement strStr() KMP 算法
- [LeetCode] 28. Implement strStr()
- leetcode 28. Implement strStr()
- [LeetCode] 28. Implement strStr()
- leetcode 28. Implement strStr()
- [leetcode]28. Implement strStr()
- [leetcode] 28. Implement strStr()
- LeetCode28. Implement strStr()
- LeetCode 28. Implement strStr()(实现子串定位)
- [Leetcode]28. Implement strStr()
- 个人记录-LeetCode 28. Implement strStr()
- [LeetCode] 28. Implement strStr() java
- leetcode 28. Implement strStr()
- 【leetcode】28. Implement strStr()
- Leetcode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- LeetCode 28. Implement strStr()
- Leetcode 28. Implement strStr()
- 28. Implement strStr() LeetCode