题解 | #kmp算法#

kmp算法

http://www.nowcoder.com/practice/bb1615c381cc4237919d1aa448083bcc

建议背住,匹配的过程和求next的过程很相似。

public class Solution {
    public int kmp (String S, String T) {
        // write code here
        int count = 0;
        int[] next = new int[S.length()];
        getNext(S, next);
        for (int i = 0, j = 0; i < T.length(); ++i) {
            if (j > 0 && S.charAt(j) != T.charAt(i)) {
                j = next[j - 1];
            }
            if (S.charAt(j) == T.charAt(i)) {
                j++;
            }
            if (j == S.length()) {
                count++;
                j = next[j-1];
            }
        }
        return count;
    }
    public void getNext(String s, int[] next) {
        int i = 1, j = 0;
        for (; i < s.length(); ++i) {
            if (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = next[j - 1];
            }
            if (s.charAt(i) == s.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
    }
}
全部评论

相关推荐

未知的命运:大佬这都找不到我还找啥啊
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务