Skip to content

Commit 5ff911d

Browse files
committed
Implement strStr()
1 parent 4e65a2f commit 5ff911d

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

src/implement_strstr.rs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/// @number 28
2+
/// @title Implement strStr()
3+
/// @url https://leetcode.com/problems/implement-strstr/
4+
/// @difficulty easy
5+
6+
7+
struct Solution;
8+
9+
impl Solution {
10+
pub fn str_str(haystack: String, needle: String) -> i32 {
11+
let haystack_len = haystack.len();
12+
let needle_len = needle.len();
13+
14+
if needle_len == 0 { return 0; }
15+
16+
let mut i = 0;
17+
'main: while (i as i32) <= (haystack_len as i32 - needle_len as i32) {
18+
let mut j = 0;
19+
if !&haystack[i..i + 1].eq(&needle[j..j + 1]) {
20+
i += 1;
21+
continue;
22+
}
23+
let mut k = i;
24+
while j < needle_len {
25+
if !&haystack[k..k + 1].eq(&needle[j..j + 1]) {
26+
i += 1;
27+
continue 'main;
28+
}
29+
k += 1;
30+
j += 1;
31+
}
32+
return i as i32;
33+
}
34+
-1
35+
}
36+
}
37+
38+
39+
#[cfg(test)]
40+
mod test {
41+
use crate::implement_strstr::Solution;
42+
43+
#[test]
44+
fn test1() {
45+
assert_eq!(2, Solution::str_str("hello".into(), "ll".into()));
46+
}
47+
48+
#[test]
49+
fn test2() {
50+
assert_eq!(-1, Solution::str_str("aaaaa".into(), "-1".into()));
51+
}
52+
53+
#[test]
54+
fn test3() {
55+
assert_eq!(0, Solution::str_str("aaaaa".into(), "".into()));
56+
}
57+
58+
#[test]
59+
fn test4() {
60+
assert_eq!(-1, Solution::str_str("".into(), "a".into()));
61+
}
62+
63+
#[test]
64+
fn test5() {
65+
assert_eq!(-1, Solution::str_str("aaaa".into(), "aaaaa".into()));
66+
}
67+
68+
#[test]
69+
fn test6() {
70+
assert_eq!(0, Solution::str_str("a".into(), "a".into()));
71+
}
72+
73+
#[test]
74+
fn test7() {
75+
assert_eq!(4, Solution::str_str("mississippi".into(), "issip".into()));
76+
}
77+
}

src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,5 @@ mod three_sum_closest;
3131
mod letter_combinations_of_a_phone_number;
3232
mod valid_parentheses;
3333
mod remove_duplicates_from_sorted_array;
34-
mod remove_element;
34+
mod remove_element;
35+
mod implement_strstr;

0 commit comments

Comments
 (0)