File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ use std:: collections:: HashMap ;
2+ use std:: collections:: HashSet ;
3+
4+ /// Given a string `s`, find the first non-repeating character in it and return
5+ /// its index. If it does not exist, return `-1`.
6+ struct Solution ;
7+
8+ impl Solution {
9+
10+ fn to_counts ( s : & str ) -> HashMap < char , usize > {
11+ let mut result = HashMap :: new ( ) ;
12+ for c in s. chars ( ) {
13+ result. entry ( c)
14+ . and_modify ( |count| { * count += 1 ; } )
15+ . or_insert ( 1 ) ;
16+ }
17+ result
18+ }
19+
20+ pub fn first_uniq_char ( s : String ) -> i32 {
21+ let counts = Self :: to_counts ( & s) ;
22+
23+ let mut result = -1 ;
24+ for ( i, c) in s. chars ( ) . enumerate ( ) {
25+ if counts[ & c] == 1 {
26+ result = i as i32 ;
27+ break ;
28+ }
29+ }
30+
31+ result
32+ }
33+
34+ }
35+
36+ #[ cfg( test) ]
37+ mod tests {
38+ use super :: Solution ;
39+
40+ #[ test]
41+ fn example_1 ( ) {
42+ let s = "leetcode" . to_string ( ) ;
43+ let result = Solution :: first_uniq_char ( s) ;
44+ assert_eq ! ( result, 0 ) ;
45+ }
46+
47+ #[ test]
48+ fn example_2 ( ) {
49+ let s = "loveleetcode" . to_string ( ) ;
50+ let result = Solution :: first_uniq_char ( s) ;
51+ assert_eq ! ( result, 2 ) ;
52+ }
53+
54+ #[ test]
55+ fn example_3 ( ) {
56+ let s = "aabb" . to_string ( ) ;
57+ let result = Solution :: first_uniq_char ( s) ;
58+ assert_eq ! ( result, -1 ) ;
59+ }
60+
61+ }
Original file line number Diff line number Diff line change @@ -30,6 +30,7 @@ pub mod swap_nodes_in_pairs; // 24
3030
3131pub mod remove_duplicates_from_sorted_array; // 26
3232pub mod remove_element; // 27
33+ pub mod find_the_index_of_the_first_occurrence_in_a_string; // 28
3334
3435pub mod range_sum_query_immutable; // 30
3536
@@ -118,6 +119,8 @@ pub mod kth_smallest_element_in_a_sorted_matrix; // 378
118119
119120pub mod ransom_note; // 383
120121
122+ pub mod first_unique_character_in_a_string;
123+
121124pub mod is_subsequence; // 392
122125
123126pub mod fizz_buzz; // 412
You can’t perform that action at this time.
0 commit comments