Skip to content

Commit be20a60

Browse files
committed
feat: init Find the Index of the First Occurrence in a String
1 parent a05a5a9 commit be20a60

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#[allow(dead_code)]
2+
pub fn str_str(haystack: String, needle: String) -> i32 {
3+
let haystack = haystack.as_bytes();
4+
let needle = needle.as_bytes();
5+
6+
if needle.len() == 0 {
7+
return 0;
8+
}
9+
10+
let mut i = 0;
11+
let mut j = 0;
12+
13+
while i < haystack.len() {
14+
if haystack[i] == needle[j] {
15+
i += 1;
16+
j += 1;
17+
if j == needle.len() {
18+
return (i - j) as i32;
19+
}
20+
} else {
21+
i = i - j + 1;
22+
j = 0;
23+
}
24+
}
25+
-1
26+
}
27+
28+
29+
#[test]
30+
fn test_str_str() {
31+
assert_eq!(str_str("hello".to_string(), "ll".to_string()), 2);
32+
assert_eq!(str_str("aaaaa".to_string(), "bba".to_string()), -1);
33+
assert_eq!(str_str("".to_string(), "".to_string()), 0);
34+
assert_eq!(str_str("a".to_string(), "".to_string()), 0);
35+
assert_eq!(str_str("".to_string(), "a".to_string()), -1);
36+
}

src/easy/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod find_the_index_of_the_first_occurrence_in_a_string;
12
pub mod longest_common_prefix;
23
pub mod merged_two_sorted_lists;
34
pub mod palindrome_linked_list;

src/easy/two_sum.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![allow(dead_code)]
12
use std::collections::HashMap;
23

34
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {

0 commit comments

Comments
 (0)