leetcode_rust/
implement_str_str.rs

1#![allow(dead_code)]
2
3// todo: alter it to KMP
4pub fn str_str(haystack: String, needle: String) -> i32 {
5    if needle.is_empty() {
6        0
7    } else if needle.len() > haystack.len() {
8        -1
9    } else {
10        let a = haystack.into_bytes();
11        let b = needle.into_bytes();
12        for i in 0..=(a.len() - b.len()) {
13            let mut j = 0;
14            while j < b.len() {
15                if a[i + j] != b[j] {
16                    break;
17                }
18                j += 1;
19            }
20            if j == b.len() {
21                return i as i32;
22            }
23        }
24        -1
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31
32    #[test]
33    fn test1() {
34        let a = "hello".to_string();
35        let b = "ll".to_string();
36        assert_eq!(str_str(a, b), 2);
37
38        let a = "aaaaa".to_string();
39        let b = "bba".to_string();
40        assert_eq!(str_str(a, b), -1);
41    }
42}