再写String indexOf KMP算法

来源:互联网 发布:php 生成订单号 编辑:程序博客网 时间:2024/06/19 01:13
class Solution {    /**     * Returns a index to the first occurrence of target in source,     * or -1  if target is not part of source.     * @param source string to be scanned.     * @param target string containing the sequence of characters to match.     */    public int strStr(String source, String target) {        //write your code here        if(source == null || target == null)            return -1;        if(target.length() == 0)            return 0;        int[] next = new int[target.length()];        int m = 0, n = -1;        next[0] = -1;        while(m < target.length() - 1) {            if(n == -1 || target.charAt(m) == target.charAt(n)) {                m++;                n++;                next[m] = n;            } else {                n = next[n];            }        }        int i = 0, j = 0;        while(j < target.length() && i < source.length()) {            if(j == -1 || source.charAt(i) == target.charAt(j)) {                i++;                j++;            } else {                j = next[j];            }        }        if(j == target.length())            return i - j;        return -1;    }}

0 0