字符串|LeetCode 28. Implement strStr()(实现子串定位)

【字符串|LeetCode 28. Implement strStr()(实现子串定位)】原题网址:https://leetcode.com/problems/implement-strstr/

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
方法一:穷举。

public class Solution { public int strStr(String haystack, String needle) { if (needle.length() == 0) return 0; if (haystack.length() < needle.length()) return -1; char[] ha = haystack.toCharArray(); char[] na = needle.toCharArray(); for(int i = 0; i < ha.length && i + na.length <= ha.length; i++) { boolean match = true; for(int j = 0; j < na.length; j++) { if (ha[i + j] != na[j]) { match = false; break; } } if (match) return i; } return -1; } }


方法二:KMP算法。

public class Solution { public int strStr(String haystack, String needle) { char[] ha = haystack.toCharArray(); char[] na = needle.toCharArray(); int[] kmp = new int[na.length]; for(int offset=Math.min(na.length-1, ha.length-na.length); offset>0; offset--) { for(int i=0; i+offset


另一种实现:

public class Solution { public int strStr(String haystack, String needle) { if (needle.length() == 0) return 0; if (haystack.length() < needle.length()) return -1; char[] ha = haystack.toCharArray(); char[] na = needle.toCharArray(); int[] kmp = new int[na.length]; for(int i = Math.min(ha.length - na.length, na.length - 2); i >= 1; i--) { for(int j = i; j < na.length - 1; j++) { if (na[j - i] == na[j]) { kmp[j + 1] = i; } else { break; } } }int h = 0, n = 0; while (h + na.length <= ha.length) { if (ha[h + n] == na[n]) { n++; if (n == na.length) return h; } else if (kmp[n] == 0) { h += Math.max(n, 1); n = 0; } else { h += kmp[n]; n -= kmp[n]; } } return -1; } }


有一篇很牛的KMP算法介绍,参考:http://blog.csdn.net/v_july_v/article/details/7041827


看了上文之后,重新写了一下,把kmp数组看成是最大公共前后缀的长度,这样理解非常方便!

public class Solution { public int strStr(String haystack, String needle) { if (needle.length() == 0) return 0; if (haystack.length() < needle.length()) return -1; char[] ha = haystack.toCharArray(); char[] na = needle.toCharArray(); int[] len = new int[na.length]; for(int i = 1; i < na.length && i <= ha.length - na.length; i++) { int j = len[i - 1]; while (j > 0 && na[j] != na[i]) j = len[j - 1]; len[i] = j + (na[j]==na[i]? 1 : 0); }int h = 0, n = 0; while (h + na.length <= ha.length) { if (ha[h + n] == na[n]) { n++; if (n == na.length) return h; } else if (n == 0) { h++; } else { h += n - len[n - 1]; n = len[n - 1]; } } return -1; } }



    推荐阅读