
// "sadbutsad" "sad" 0
// "leetcode" "leeto" -1
// "你好吗" "好" 3 额外加的
// 内置的 str::find 函数
pub fn str_str(haystack: String, needle: String) -> i32 {
if needle.is_empty() {// 空串匹配任意字符串 虽然题目说不会有空字符串
return 0;
}
if let Some(pos) = haystack.find(&needle) {// 查找第一个匹配项 汉字占三个字节
pos as i32
} else {
-1
}
}
// kmp 算法 辅助函数用于计算next数组
pub fn str_str2(haystack: String, needle: String) -> i32 {
let m = needle.len();
let n = haystack.len();
if m == 0 {
return 0;
}
let mut lps = vec![0; m];
let mut j = 0; // needle index
// Preprocess the pattern (calculate lps array)
compute_lps(&needle.as_bytes(), m, &mut lps);//关联函数调用要self
let haystack_bytes = haystack.as_bytes();
let needle_bytes = needle.as_bytes();
let mut i = 0; // haystack index
while i < n {
if needle_bytes[j] == haystack_bytes[i] {
j += 1;
i += 1;
}
else if i < n && needle_bytes[j] != haystack_bytes[i] {
if j != 0 {
j = lps[j - 1];
} else {
i += 1;
}
}
if j == m {
return (i - j) as i32;
}
}
-1
}
fn compute_lps(pattern: &[u8], m: usize, lps: &mut Vec<usize>) {
let mut len = 0;
let mut i = 1;
lps[0] = 0; // lps[0] is always 0
while i < m {
if pattern[i] == pattern[len] {
len += 1;
lps[i] = len;
i += 1;
} else {
if len != 0 {
len = lps[len - 1];
} else {
lps[i] = 0;
i += 1;
}
}
}
}
fn main() {
assert_eq!(str_str("sadbutsad".to_string(), "sad".to_string()), 0);
assert_eq!(str_str("leetcode".to_string(), "leeto".to_string()), -1);
assert_eq!(str_str("你好吗".to_string(), "好".to_string()), 3);
assert_eq!(str_str2("sadbutsad".to_string(), "sad".to_string()), 0);
assert_eq!(str_str2("leetcode".to_string(), "leeto".to_string()), -1);
assert_eq!(str_str2("你好吗".to_string(), "好".to_string()), 3);
}
8625

被折叠的 条评论
为什么被折叠?



