Go实现KMP和Sunday算法
2024-10-21 17:35:48
KMP
1 func KMP(str, substr string) int {
2 if substr == "" {
3 return 0
4 }
5 strLen := len(str)
6 subLen := len(substr)
7 next := make([]int, subLen)
8 for i, j := 1, 0; i < subLen; i++ {
9 for j > 0 && substr[i] != substr[j] {
10 j = next[j-1]
11 }
12 if substr[i] == substr[j] {
13 j++
14 }
15 next[i] = j
16 }
17 for i, j := 0, 0; i < strLen; i++ {
18 for j > 0 && str[i] != substr[j] {
19 j = next[j-1]
20 }
21 if str[i] == substr[j] {
22 j++
23 }
24 if j == subLen {
25 return i - subLen + 1
26 }
27 }
28 return -1
29 }
Sunday
func Sunday(str, substr string) int {
if len(substr) == 0 {
return 0
}
strLen := len(str)
subLen := len(substr)
if subLen > strLen {
return -1
}
m := make(map[rune]int, 0)
for index, c := range substr {
m[c] = index
}
start, compareCount := 0, 0
for start+subLen <= strLen {
compareCount = 0
for str[start+compareCount] == substr[compareCount] {
compareCount++
if compareCount == subLen {
return start
}
}
checkIndex := start + subLen
var lastIndex int
if checkIndex < strLen {
lastIndex = m[rune(str[checkIndex])]
} else {
lastIndex = -1
}
if lastIndex != -1 {
start += subLen - lastIndex
} else {
start += start + subLen + 1
}
}
return -1
}
最新文章
- oracle 学习摘录
- jQuery-2.1.4.min.js:4 Uncaught TypeError: Illegal invocation
- SNF开发平台WinForm之十二-发送手机短信功能调用-金笛-SNF快速开发平台3.3-Spring.Net.Framework
- 使用unetbootin制作Debian安装U盘
- Java基础(52):ClassCastException详解(转)
- LAMP开发之环境搭建(2014.12.7在ubuntu下)
- UVa 10868 (物理) Bungee Jumping
- truncate 、delete与drop三者的异同
- Delphi颜色的表示(一共5种表示法)
- 手动为maven的本地仓库添加JAR
- Memory Analyzer Tool 使用手记
- django —— KindEditor - 跨域上传图片
- [HAOI2010]最长公共子序列(LCS+dp计数)
- 小程序webview应用实践
- c#特性学习(1)
- aspnet_regiis -i VS 20XX 的开发人员命令提示符
- HUD 2639 Bone Collector II
- Python的优雅写法
- iOS笔记,开发经验总结【持续更新】
- Selenium WebDriver 下 plugin container for firefox has stopped working