leetcode 28 rust
题目
代码
pub fn str_str(haystack: String, needle: String) -> i32 {
let hay_len = haystack.len() as i32;
let ned_len = needle.len() as i32;
if hay_len < ned_len {
return -1;
}
if ned_len == 0 {
return 0;
}
for i in 0..(hay_len-ned_len+1) as i32 {
for j in 0..ned_len as i32 {
match haystack.chars().nth((i+j) as usize).cmp(&needle.chars().nth((j) as usize)) {
std::cmp::Ordering::Less | std::cmp::Ordering::Greater => {
break;
},
std::cmp::Ordering::Equal => {
if j == (ned_len-1) {
return i;
}
},
}
}
}
-1
}
测试
#[cfg(test)]
mod tests{
use super::*;
#[test]
fn test_1(){
assert_eq!(str_str("hello".to_string(),"ll".to_string()),2);
}
#[test]
fn test_2(){
assert_eq!(str_str("aaaaa".to_string(),"bba".to_string()),-1);
}
}
posted on 2021-04-08 16:24 GeniusOfCX 阅读(47) 评论(0) 编辑 收藏 举报