Java for LeetCode 028 Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
解题思路一:
暴力枚举,JAVA实现如下:
static public int strStr(String haystack, String needle) { for(int i=0;i<=haystack.length()-needle.length();i++) if(haystack.substring(i, i+needle.length()).equals(needle)) return i; return -1; }
解题思路二:
经典的KMP算法
参考链接:
http://kb.cnblogs.com/page/176818/
http://blog.csdn.net/zxasqwedc/article/details/41956381
JAVA 实现
static public int strStr(String haystack, String needle) { int[] next = new int[needle.length()+1]; int i = 0, j = -1; //i可以代表索引,其实也可以理解为一个间隔,j代表前面已匹配的 //next[1,next.length-1] 恰好表示部分匹配值 next[0] = -1; while (i < needle.length()) { if (j == -1 || needle.charAt(i) == needle.charAt(j)) { i++; j++; next[i] = j; } else j = next[j]; } i = 0; j = 0; while (i < haystack.length()) { if (j == -1 || haystack.charAt(i) == needle.charAt(j)) { i++; j++; } else j = next[j];//是next[j]不是next[j-1],算法核心 if (j == needle.length()) return i - needle.length(); } return -1; }