Skip to content

Commit dce23e2

Browse files
committed
Added Find the Index of the First Occurrence in a String
1 parent 5c9476e commit dce23e2

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/// Given two strings `needle` and `haystack`, return the index of the first
2+
/// occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of
3+
/// `haystack`.
4+
struct Solution;
5+
6+
impl Solution {
7+
8+
pub fn str_str(haystack: String, needle: String) -> i32 {
9+
let mut result = -1;
10+
11+
let h: Vec<char> = haystack.chars().collect();
12+
let n: Vec<char> = needle.chars().collect();
13+
14+
let hlen = h.len();
15+
let nlen = n.len();
16+
17+
for i in 0..hlen {
18+
let mut index = 0;
19+
while (index < nlen) && (i + index < hlen) && h[i+index] == n[index] {
20+
index += 1;
21+
}
22+
if index == nlen {
23+
result = i as i32;
24+
break;
25+
}
26+
}
27+
28+
result
29+
}
30+
31+
}
32+
33+
#[cfg(test)]
34+
mod tests {
35+
use super::Solution;
36+
37+
#[test]
38+
fn example_1() {
39+
let haystack = "sadbutsad".to_string();
40+
let needle = "sad".to_string();
41+
let result = Solution::str_str(haystack, needle);
42+
assert_eq!(result, 0);
43+
}
44+
45+
#[test]
46+
fn example_2() {
47+
let haystack = "leetcode".to_string();
48+
let needle = "leeto".to_string();
49+
let result = Solution::str_str(haystack, needle);
50+
assert_eq!(result, -1);
51+
}
52+
53+
#[test]
54+
fn middle() {
55+
let haystack = "goodbye".to_string();
56+
let needle = "od".to_string();
57+
let result = Solution::str_str(haystack, needle);
58+
assert_eq!(result, 2);
59+
}
60+
61+
#[test]
62+
fn end() {
63+
let haystack = "cartoon".to_string();
64+
let needle = "toon".to_string();
65+
let result = Solution::str_str(haystack, needle);
66+
assert_eq!(result, 3);
67+
}
68+
69+
#[test]
70+
fn off_end() {
71+
let haystack = "national".to_string();
72+
let needle = "ale".to_string();
73+
let result = Solution::str_str(haystack, needle);
74+
assert_eq!(result, -1);
75+
}
76+
77+
}

0 commit comments

Comments
 (0)