leetcode_rust/
first_unique_character_in_a_string.rs1#![allow(dead_code)]
2
3pub fn first_uniq_char(s: String) -> i32 {
4 use std::collections::HashMap;
5
6 let s = s.into_bytes();
7 let mut map = HashMap::new();
9
10 for ch in s.clone() {
11 match map.get_mut(&ch) {
12 Some(v) => {
13 *v += 1;
14 }
15 None => {
16 map.insert(ch, 1);
17 }
18 }
19 }
20
21 let mut count = 0;
22 for ch in s {
23 match map.get(&ch) {
24 Some(&v) => {
25 if v == 1 {
26 return count;
27 }
28 }
29 None => unreachable!(),
30 }
31 count += 1;
32 }
33 -1
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn test1() {
42 let s = "leetcode".to_string();
43 assert_eq!(first_uniq_char(s), 0);
44 let s = "loveleetcode".to_string();
45 assert_eq!(first_uniq_char(s), 2);
46 }
47}