1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

Make string.index() use a linear KMP search

This commit is contained in:
Undumendil 2019-06-25 19:05:24 +03:00 committed by Alexander Medvednikov
parent fc7ac25a98
commit d1a1f74d33

View File

@ -349,23 +349,36 @@ pub fn (s string) substr(start, end int) string {
return res return res
} }
// KMP search
pub fn (s string) index(p string) int { pub fn (s string) index(p string) int {
if p.len > s.len { if p.len > s.len {
return -1 return -1
} }
mut i := 0 mut prefix := [0]
for i < s.len {
mut j := 0 mut j := 0
mut ii := i for i := 1; i < p.len; i++ {
for j < p.len && s[ii] == p[j] { for p[j] != p[i] && j > 0 {
j = prefix[j - 1]
}
if p[j] == p[i] {
j++
}
prefix << j
}
j = 0
for i := 0; i < s.len; i++ {
for p[j] != s[i] && j > 0 {
j = prefix[j - 1]
}
if p[j] == s[i] {
j++ j++
ii++
} }
if j == p.len { if j == p.len {
return i prefix.free()
return i - p.len + 1
} }
i++
} }
prefix.free()
return -1 return -1
} }