数据结构——字符串-kmp算法
2022/1/10 20:07:55
本文主要是介绍数据结构——字符串-kmp算法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.it.alg.kmp; import java.util.Arrays; import java.util.stream.Collectors; public class NextTest { public static void main(String[] args) { String s = "aaab"; System.out.println(s); System.out.println(Arrays.stream(next(s)).boxed().collect(Collectors.toList())); System.out.println(Arrays.stream(nextVal(s)).boxed().collect(Collectors.toList())); System.out.println(kmp(s, "b")); } public static int[] next(String sub) { int[] next = new int[sub.length()]; char[] chars = sub.toCharArray(); int i = 0, j = -1; next[0] = -1; while (i < chars.length - 1) { if (j == -1 || chars[i] == chars[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } for (int item = 0; item < next.length; item++) { next[item]++; } return next; } public static int[] nextVal(String sub) { int[] nextVal = new int[sub.length()]; char[] chars = sub.toCharArray(); int i = 0, j = -1; nextVal[0] = -1; while (i < chars.length - 1) { if (j == -1 || chars[i] == chars[j]) { if (chars[++i] != chars[++j]) { nextVal[i] = j; } else { nextVal[i] = nextVal[j]; } } else { j = nextVal[j]; } } for (int item = 0; item < nextVal.length; item++) { nextVal[item]++; } return nextVal; } public static int kmp(String str, String sub) { char[] strChars = str.toCharArray(); char[] subChars = sub.toCharArray(); int[] nextVal = nextVal(sub); int i = 1, j = 1; while (i <= str.length() && j <= sub.length()) { if (j == 0 || strChars[i - 1] == subChars[j - 1]) { i++; j++; } else { j = nextVal[j - 1]; } } if (j > sub.length()) return i - sub.length() - 1; return -1; } }
运行结果:
这篇关于数据结构——字符串-kmp算法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-082024年常用的情绪识别API
- 2025-01-07如何利用看板工具优化品牌内容创作与审批,确保按时发布?
- 2025-01-07百万架构师第十一课:源码分析:Spring 源码分析:Spring源码分析前篇|JavaGuide
- 2025-01-07质量检测标准严苛,这 6 款办公软件达标了吗?
- 2025-01-07提升品牌活动管理的效率:看板工具助力品牌活动日历的可视化管理
- 2025-01-07宠物商场的精准营销秘籍:揭秘看板软件的力量
- 2025-01-07“30了,资深骑手” | 程序员能有什么好出路?
- 2025-01-07宠物公园的营销秘籍:看板软件如何帮你精准触达目标客户?
- 2025-01-07从任务分解到资源优化:甘特图工具全解析
- 2025-01-07企业升级必备指南:从传统办公软件到SaaS工具的转型攻略