KMP算法 leetcode-28
[leetcode 28题](https://leetcode-cn.com/problems/implement-strstr/)
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入:haystack = "hello", needle = "ll"
输出:2
示例 2:输入:haystack = "aaaaa", needle = "bba"
输出:-1
示例 3:输入:haystack = "", needle = ""
输出:0来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution { public int strStr(String haystack, String needle) { int m = haystack.length();//i遍历 int n = needle.length();//j遍历 if(needle.length()==0){ return 0; } int[] prefix = prefix(needle); int i = 0; int j = 0; for(i = 0; i<m;i++){ while(j>0&& needle.charAt(j) != haystack.charAt(i)){ j = prefix[j-1]; } if(needle.charAt(j) == haystack.charAt(i)){ j++; } if(j == n){ return i-n+1; } } return -1; } //计算模式串的前缀表 private int[] prefix(String needle){ int beforeEnd = 0; int[] prefix = new int[needle.length()]; for(int afterEnd = 1; afterEnd<needle.length(); afterEnd++){ while(beforeEnd > 0 && needle.charAt(beforeEnd)!=needle.charAt(afterEnd)){ beforeEnd = prefix[beforeEnd-1]; } if(needle.charAt(afterEnd) == needle.charAt(beforeEnd)){ beforeEnd++; } prefix[afterEnd] = beforeEnd; } return prefix; } }
本文来自博客园,作者:{zhongweiLeex},转载请注明原文链接:{https://www.cnblogs.com/lzw6/}

浙公网安备 33010602011771号