题解 | #java KMP算法#

kmp算法

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

KMP算法算是字符串匹配问题中的经典了,不用过多的装饰,直接写一个经典的写法:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 计算模板串S在文本串T中出现了多少次
     * @param S string字符串 模板串
     * @param T string字符串 文本串
     * @return int整型
     */
    public int kmp (String S, String T) {
        // write code here
        char[] s = S.toCharArray();
        char[] t = T.toCharArray();
        int[] next = new int[s.length];
        int res = 0;

        initNext(next, s); // 生成next数组

        for (int i = 0, j = 0; i < t.length; i++) {
            if (j > 0 && t[i] != s[j]) {
                j = next[j - 1];
            }
            if (t[i] == s[j]) {
                j++;
            }
            if (j == s.length) {
                res++;
                j = next[j - 1];
            }
        }

        return res;
    }

    private void initNext (int[] next, char[] s) {

        for (int i = 1, j = 0; i < s.length; i++) {
            while (j > 1 && s[i] != s[j]) {
                j = next[j - 1];
            }
            if (s[i] == s[j]) {
                j++;
            }
            next[i] = j;
        }
    }
} 
全部评论

相关推荐

当初高考报计算机真是造大孽了啊!卷的飞起!哪都是计算机的人,考研,考公,找工作全他奶的计算机的人,太难了。国企也是。关键一届比一届卷,造大孽了!
_Lyrics_:因为计算机,没有体验到快乐的大学研究生时光,好不容易修完课程就要出去实习,看着别人专业可以一起搓麻将,游山玩水,而我却要自己一个人住在北上不到十平米的出租屋,每天两点一线
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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