File tree Expand file tree Collapse file tree 2 files changed +79
-1
lines changed Expand file tree Collapse file tree 2 files changed +79
-1
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change @@ -31,4 +31,5 @@ mod three_sum_closest;
3131mod letter_combinations_of_a_phone_number;
3232mod valid_parentheses;
3333mod remove_duplicates_from_sorted_array;
34- mod remove_element;
34+ mod remove_element;
35+ mod implement_strstr;
You can’t perform that action at this time.
0 commit comments