当前位置:网站首页>KMP 字符串匹配问题
KMP 字符串匹配问题
2022-08-01 21:34:00 【chengqiuming】
一 原问题链接
【模板】KMP字符串匹配 - 洛谷https://www.luogu.com.cn/problem/P3375
二 输入和输出
1 输入
第 1 行为字符串 s1,第 2 行为字符串 s2。字符串只含大写英文字母。
2 输出
首先输出若干行,每行一个整数,按从小到大的顺序输出 s2 在 s1 中出现的位置。最后一行输出 |s2| 个整数,第 i 个整数表示 s2 的长度为 i 的前缀的最长 border 的长度。
三 输入和输出样例
1 输入样例
ABABABC
ABA
2 输出样例
1
3
0 0 1
四 分析
本问题实质上是模式匹配和求解 KMP 算法中 next[] 数组的问题。
五 算法设计
1 输入字符串 s 和 t,采用 KMP 算法从头开始查找 t 在 s 中出现的位置。
2 求解字符串 t 的 next[] 数组。next[i] 表示 t 的长度为 i 的前缀的最长 border 的长度。
六 代码
package p3375;
import java.util.Scanner;
public class P3375 {
static int slen;
static int tlen;
static int next[] = new int[1000000 + 5];
// 求模式串 T 的 next 函数值
static void get_next(String t) {
int j = 0, k = -1;
next[0] = -1;
while (j < tlen) {//模式串t的长度
if (k == -1 || t.charAt(j) == t.charAt(k))
next[++j] = ++k;
else
k = next[k];
}
}
static void KMP(String s, String t) {
int i = 0, j = 0;
slen = s.length();
tlen = t.length();
get_next(t);
while (i < slen) {
if (j == -1 || s.charAt(i) == t.charAt(j)) { // 如果相等,则继续比较后面的字符
i++;
j++;
} else
j = next[j]; // j 回退到 next[j]
if (j == tlen) { // 匹配成功
System.out.println(i - tlen + 1);
j = next[j]; // 不允许重叠,j从0重新开始,如果允许重叠,j=nex[j]
}
}
}
public static void main(String[] args) {
String s, t;
Scanner scanner = new Scanner(System.in);
s = scanner.nextLine();
t = scanner.nextLine();
KMP(s, t);
for (int i = 1; i <= tlen; i++)
System.out.print(next[i] + " ");
}
}七 测试
绿色为输出,白色为输出。

边栏推荐
猜你喜欢

Unity Shader 常规光照模型代码整理

牛血清白蛋白刺槐豆胶壳聚糖缓释纳米微球/多西紫杉醇的纳米微球DTX-DHA-BSA-NPs

LVS负载均衡群集

C Expert Programming Chapter 1 C: Through the Fog of Time and Space 1.4 K&R C

Based on php film and television information website management system acquisition (php graduation design)
![[Chinese tree tags - CTB]](/img/f4/b985da2ff83b2a9ab4eebb8bd060bf.png)
[Chinese tree tags - CTB]

19 Lectures on Disassembly of Multi-merchant Mall System Functions - Invoice Management on the Platform

10 Practical Uses of NFTs (NFT System Development)

ARFoundation Getting Started Tutorial U2-AR Scene Screenshot Screenshot

基于php旅游网站管理系统获取(php毕业设计)
随机推荐
Spark shuffle调优
Interview Blitz 70: What are sticky packs and half packs?How to deal with it?
你居然不懂Bitmap和Drawable? 相关知识大扫盲
方舟:生存进化官服和私服区别
Spark练习题+答案
C Pitfalls and Defects Chapter 7 Portability Defects 7.8 Size of Random Numbers
ModuleNotFoundError: No module named ‘yaml‘
C pitfalls and pitfalls Chapter 8 Suggestions and answers 8.2 Answers
HCIP---多生成树协议相关知识点
【C语言实现】整数排序-四种方法,你都会了吗、
Based on php film and television information website management system acquisition (php graduation design)
Realize the superposition display analysis of DWG drawing with CAD in Cesium
【建议收藏】ヾ(^▽^*)))全网最全输入输出格式符整理
C Pitfalls and pitfalls Appendix B Interview with Koenig and Moo
C expert programming
C Pitfalls and Defects Chapter 5 Library Functions 5.5 Library Function Signal
LeetCode952三部曲之一:解题思路和初级解法(137ms,超39%)
C语言_枚举类型介绍
2022牛客多校联赛第五场 题解
Shell programming conditional statement