Leetcode 28. Implement strStr()
28. Implement strStr()
- Total Accepted: 125882
- Total Submissions: 484537
- Difficulty: Easy
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:最朴素的想法就是2个指针的做法。还有直接可以用KMP算法做。具体可以看下面的链接:
1. http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
2. http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/
关于KMP,其实比较重要的就是“部分匹配表”lps。lps[i]表示的是以i位置为结尾,以0位置为开始的字符串中,前缀和后缀相同时的最大长度。也可以理解为母串Str[i,i+1,...,i+j]和子串str[0,...,j]匹配冲突(Str[i,i+1,...,i+j-1]和子串str[0,...,j-1]匹配成功)时,子串的j指针应该回到lps[j - 1]的位置成为str[j],重新与Str[i+j]进行比较。这里lps[j]可以理解为以j结束的字符串中,前缀和后缀匹配时,前缀最后一个元素的下一个位置。
代码:
朴素的做法:
1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 int j, end = haystack.size() - needle.size() + 1; 5 for (int i = 0; i < end; i++) { 6 for (j = 0; j < needle.size() && haystack[i+j] == needle[j]; j++); 7 if (j == needle.size()) return i; 8 } 9 return -1; 10 } 11 };
KMP的做法:
1 class Solution { 2 public: 3 int strStr(string haystack, string needle) { 4 vector<int> lps = KMP(needle); 5 int i, j; 6 for (i = 0, j =0; i < haystack.size() && j < needle.size(); ) { 7 if (haystack[i] == needle[j]) { 8 i++; 9 j++; 10 } 11 else{ 12 if (!j) i++; 13 else j = lps[j-1]; 14 } 15 } 16 return j == needle.size() ? i - j : -1; 17 } 18 private: 19 vector<int> KMP(string needle){ 20 vector<int> lps(needle.size(),0);//lps[i]存储的是与i位置相同的j(i>j)位置的后一个元素的位置 21 int len = 0; 22 for (int i = 1;i < needle.size();) { 23 if (needle[i] == needle[len]) lps[i++] = ++len; 24 else { 25 if (!len)lps[i++] = 0; 26 else len = lps[len - 1]; 27 } 28 } 29 return lps; 30 } 31 };