代码随想录-KMP算法

 LeetCode28:

 . - 力扣(LeetCode)


public class KMP {
    public static void main(String[] args) {
        KMP kmp=new KMP();
        kmp.strStr("aabaabaaf","aabaaf");
    }
    public int strStr(String haystack, String needle) {
        //获取next数组
        int[] next=getNext(needle);
        //根据next数组,进行匹配
        int i=0;
        for (int j = 0; j < haystack.length()&&j+needle.length()<haystack.length(); j++) {
            while (i>0&&haystack.charAt(j)!=needle.charAt(i)){
                i=next[i-1];
            }
            if (haystack.charAt(j)==needle.charAt(i)){
                i++;
            }
            if (i==needle.length()){
                return j-i+1;
            }
        }
        return -1;
    }

    private int[] getNext(String needle) {
        int[] next=new int[needle.length()];
        next[0]=0;
        int j=0; //前缀的末尾,也是最长相等前后缀的长度
        int i;//后缀的末尾
        for (i = 1; i <needle.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;
    }

}

LeetCode459:
. - 力扣(LeetCode)


public class LeetCode459 {
    public boolean repeatedSubstringPattern(String s) {
        //查找子串,就是查找s.length-最长前后缀的长度对应的子串
        int[] next = getNext(s);
        if (next[s.length()-1]!=0&&(s.length()%(s.length()-next[s.length()-1])==0)){
            return true;
        }
        return false;
    }
    private int[] getNext(String model){
        int[] next=new int[model.length()];
        next[0]=0;
        int j=0; //前缀的尾部,也是最长前后缀的长度
        int i;//后缀的尾部
        for (i = 1; i <model.length(); i++) {
            while (j>0&&model.charAt(j)!=model.charAt(i)){
                j=next[j-1];
            }
            if (model.charAt(j)==model.charAt(i)){
                j++;
            }
            next[i]=j;
        }
        return next;
    }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-12 07:46:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-12 07:46:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-12 07:46:03       82 阅读
  4. Python语言-面向对象

    2024-04-12 07:46:03       91 阅读

热门阅读

  1. Liunx和Windows中重启MySql

    2024-04-12 07:46:03       31 阅读
  2. 浅谈-“cin 输入弊端”

    2024-04-12 07:46:03       38 阅读
  3. 用php编写网站源码的一些经验

    2024-04-12 07:46:03       41 阅读