LeetCode-28-Implement strStr()(字符串匹配)

来源:互联网 发布:2017java不好找工作了 编辑:程序博客网 时间:2024/06/09 15:53

Q:

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Analysis:

第一反应就是用基础的KMP算法来实现,也可用其他字符串匹配算法如BM等算法。

Code:

public class Solution {    public static int[] getNextVal(String needle) {        int[] next = new int[needle.length()];        next[0] = -1;        int k = -1;// 前缀索引        int j = 0;// 后缀索引        while (j < needle.length() - 1) {             //needle.charAt(k)表示前缀,needle.charAt(j)表示后缀                if (k == -1 || needle.charAt(j)==needle.charAt(k)) {                ++k;                ++j;                next[j] = k;            } else {                k = next[k];            }        }        return next;    }    public int strStr(String haystack, String needle) {        int i=0;        int j=0;        int hayLen=haystack.length();        int needLen=needle.length();        if(needLen==0){            return 0;        }        if (hayLen==0) {            return -1;        }        int []next=getNextVal(needle);        while(i<hayLen&&j<needLen){            if(j==-1||haystack.charAt(i)==needle.charAt(j)){                //①如果j = -1,或者当前字符匹配成功(即S[i] == P[j]),都令i++,j++                i++;                j++;            }else{                //②如果j != -1,且当前字符匹配失败(即S[i] != P[j]),则令 i 不变,j = next[j]                      //next[j]即为j所对应的next值                    j=next[j];            }        }        if(j==needLen){            return i-j;        }else{            return -1;        }    }}