impl Solution {
pub fn get_next(needle:&Vec<u8>, mut next: Vec<usize>)->Vec<usize>{
let mut i = 1;
let mut j = 0;
while i < needle.len()
{
if needle[i] == needle[j]
{
j=j+1;
next[i]=j;
i=i+1;
}
else{
if j!=0{
j = next[j-1];
}
else{
next[i]=0;
i=i+1;
}
}
}
next
}
pub fn kmp(haystack:&Vec<u8>,needle:&Vec<u8>) -> i32{
let m = needle.len();
if m == 0 {
return 0;
}
if haystack.len()<needle.len(){
return -1;
}
let mut next = Solution::get_next(needle,vec![0usize;m]);
let mut i=0;
let mut j=0;
while i<haystack.len() && j<needle.len(){
if haystack[i]==needle[j]
{
i=i+1;
j=j+1;
}else
{
if j!=0{
j=next[j-1];
}
else { i=i+1;}
}
}
if j == needle.len(){
(i-j) as i32
}
else{
-1
}
}
pub fn str_str(haystack: String, needle: String) -> i32 {
return Solution::kmp(&haystack.as_bytes().to_vec(),&needle.as_bytes().to_vec());
}
}