

go 实现indexOf,leetCode28
source link: https://studygolang.com/articles/35577
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

go indexOf
indexOf
indexOf(s, p string) 函数会返回p在s中首次出现的位置,倘如没有则返回-1,本次使用之前提到过的kmp算法来作为indexOf的核心,并用来解决leetcode28题
func strStr(haystack string, needle string) int {
return indexOf(haystack, needle)
}
func indexOf(s, p string) int {
if len(p) == 0 {
return 0
}
next := make([]int, len(p))
next[0] = -1
j := -1
for i := 1; i < len(p); i++ {
for j != -1 && p[i] != p[j+1] {
j = next[j]
}
if p[i] == p[j+1] {
j++
}
next[i] = j
}
j = -1
for i := 0; i < len(s); i++ {
for j != -1 && s[i] != p[j+1] {
j = next[j]
}
if s[i] == p[j+1] {
j++
}
if j == len(p) - 1 {
return i - j
}
}
return -1
}
Recommend
-
146
在上篇中,我们已经讨论过如何去实现一个 Map 了,并且也讨论了诸多优化点。在下篇中,我们将继续讨论如何实现一个线程安全的 Map。说到线程安全,需要从概念开始说起。 线程安全就是如果你的代码块所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这...
-
119
给 String 实现一个安全的 subscript 方法 发表于 2017-10-09 更新于 2022-05-11 本文字数: 2.8k完整的实现:
-
33
#方法一:使用string.Contains方法 string.Contains是大小写敏感的,如果要用该方法来判断一个string是否包含某个关键字keyword,需要把这个string和这个key
-
48
作者八路(企业代号名),目前负责贝壳找房商业化方向的前端工作。 提到常见的字符串匹配算法,一般来说我们会想到一个是朴素算法(...
-
26
简介 最近做项目的时候,发现无论是前端还是后端,indexOf出现的概率都非常频繁,今天我们来看下他的实现原理吧! indexOf的含义 : 给定一个字符串去匹配另一个字符串的下标,如...
-
15
A quiz about type-coercion, indexOf return values, and the principle of lol whoops a bug.A quiz about type-coercion, indexOf return values, and the principle of lol whoops a bug. 03 Mar 2014 Given the following vers...
-
2
IndexOf for chain space advertisements There is a space in the string, but when I run program, it returns -1, t...
-
6
Golang strings.Index = JavaScript String indexOf() Theory and Practice ≡
-
6
indexOf 的 >=0 与 !==-1 问题 在一个项目中,别的同事用到了 indexOf,我一般判断都是写成 >=0,而他写作 !==-1...
-
4
April 6, 2023 /
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK