只实现kmp算法的思想,数据类型没有弄成String,一方面是String类型不能直接索引,另一方面也是懒。这个其实不难,处理下数据类型,不嫌弃的话直接用Vec就可以了
fn kmp(s: Vec<i32>, p: Vec<i32>) -> (bool, usize) {
let length_p = p.len();
let mut next = vec![0];
// 生成next数组
for i in 1..length_p {
if p[next[i - 1]] == p[i] {
next.push(next[i - 1] + 1);
} else {
next.push(0);
}
}
let length_s = s.len();
let (mut i, mut j) = (0, 0);
// i是指向原数组,j是指向匹配数组
while i < length_s {
if s[i] == p[j] {
i += 1;
j += 1;
} else if j != 0 {
j = next[j - 1];
} else {
i += 1
}
if j == length_p {
return (true, i - j);
}
}
(false, 0)
}
fn main() {
let s = vec![78,43,2,43,12,5,43,321,76,48,3,45,24,5,5,5,5,5,5,5,5,6,5,5,52,0];
let a = vec![5, 5, 6, 5, 5, 52];
println!("{:?}",kmp(s, a));
}