1 Star 6 Fork 1

蔚蔚樱软件开发/AlgoHub

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
KMP.java 1.53 KB
一键复制 编辑 原始数据 按行查看 历史
ljfirst 提交于 2022-10-31 23:58 +08:00 . feat: update
package DataStructure.stringOps.stringCompare;
/**
* @author 蔚蔚樱
* @version 1.0
* @date 2019-7-8 04:57:00
* @author-Email micromicrohard@outlook.com
* @blogURL https://blog.csdn.net/Micro_Micro_Hard/article/details/95072616
* @description KMP 字符串匹配算法
*/
public class KMP implements StringCompare {
public boolean compareMethod(String source, String target) {
return check(source, target) && kmp(source, target);
}
//kmp ƥ�����
public boolean kmp(String source, String pattern) {
int sourcePoint = 0;
int patternPoint = 0;
int[] next = getNext(pattern);
while (sourcePoint < source.length() && patternPoint < pattern.length()) {
if (patternPoint == -1 || source.charAt(sourcePoint) == pattern.charAt(patternPoint)) {
sourcePoint++;
patternPoint++;
} else {
patternPoint = next[patternPoint];
}
}
if (patternPoint == pattern.length()) {
return true;
}
return false;
}
public int[] getNext(String s) {
int[] next = new int[s.length()];
int point = 0;
int prefix = -1;
next[0] = -1;
while (point < s.length() - 1) {
if (prefix == -1 || s.charAt(prefix) == s.charAt(point)) {
point++;
prefix++;
next[point] = prefix;
} else {
prefix = next[prefix];
}
}
return next;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/micromicrohard/algo-hub.git
git@gitee.com:micromicrohard/algo-hub.git
micromicrohard
algo-hub
AlgoHub
master

搜索帮助