代码训练营day09

主要内容:熟悉kmp算法

目录

  1. kmp算法,标准字符串匹配目标字符串的第一个下标
  2. 重复字符串

一、实现kmp算法

重点是如何求next数组,getNext 和 getKmp代码看似很相似,但实际上作用是不一样的。getNext是为了把数j存入next数组中,而getKmp则是为了获取值,从而跳过几个字符串

public class KmpStr {
    public int strStr(String haystack, String needle) {

        int[] next = getNext(needle);
        int i = getKmp(next, haystack, needle);
        return i;
    }

    public int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        int i; // next数组的指针,也是遍历标准字符串的指针
        int j = 0;
        next[0] = 0;	
        // i 从1开始
        for (i = 1; i < next.length; i++) {
            while (j > 0 && needle.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                j++;
            }

            next[i] = j;
        }
        return next;
    }

    public int getKmp(int[] next, String haystack, String needle) {

        for (int i = 0, j = 0; i < haystack.length(); i++) {

            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            // TODO: 2024/5/17  也就是这里和前面不一样,前面是和自己的前后进行比较,这个是和目标字符串进行比较 
            if (haystack.charAt(i) == needle.charAt(j)) {   
                j++;
            }
            if (j == needle.length()) {  // 全部匹配
                return i - j + 1;      // 返回匹配的第一个索引
            }
        }
        return -1;
    }
}

—————————————————————————————————————————

二、重复字符串

public class RepeatStrCount {

    public boolean repeatedSubstringPattern01(String s) {
        String str = s + s;
        return str.substring(1, str.length() - 1).contains(s);
    }


    /**
     * 求kmp 减减的形式   j =-1 , i =1 ; j = 0 ,i =2;
     * @param s
     * @return
     */
    public boolean repeatedSubstringPattern02(String s) {
        if (s.equals("")) return false;

        int len = s.length();
        // 原串加个空格(哨兵),使下标从1开始,这样j从0开始,也不用初始化了
         // todo next[0] = 0 , 直接省略了
        s = " " + s;
        char[] chars = s.toCharArray();
        int[] next = new int[len + 1];

        // 构造 next 数组过程,j从0开始(空格),i从2开始
        for (int i = 2, j = 0; i <= len; i++) {
            // 匹配不成功,j回到前一位置 next 数组所对应的值
            while (j > 0 && chars[i] != chars[j + 1]) j = next[j];
            // 匹配成功,j往后移
            if (chars[i] == chars[j + 1]) j++;
            // 更新 next 数组的值
            next[i] = j;
        }

        // 最后判断是否是重复的子字符串,这里 next[len] 即代表next数组末尾的值
        if (next[len] > 0 && len % (len - next[len]) == 0) {
            return true;
        }
        return false;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值