-
Notifications
You must be signed in to change notification settings - Fork 20
/
0387_first_unique_character_in_a_string.rs
67 lines (59 loc) · 1.63 KB
/
0387_first_unique_character_in_a_string.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
//!
//! Examples:
//!
//! s = "leetcode"
//! return 0.
//!
//! s = "loveleetcode",
//! return 2.
//!
//! Note: You may assume the string contain only lowercase letters.
use std::collections::HashMap;
struct Solution;
impl Solution {
pub fn first_uniq_char(s: String) -> i32 {
let mut map: HashMap<char, i32> = HashMap::new();
s.chars().into_iter().enumerate().for_each(|(index, c)| {
if let Some(v) = map.get_mut(&c) {
if *v != i32::max_value() {
// use i32::max_value() to indicate this char has appeared more than once.
*v = i32::max_value();
}
} else {
map.insert(c, index as i32);
}
});
let min_index = map.iter().min_by(|(c1, index1), (c2, index2)| {
index1.cmp(index2)
});
match min_index {
Some((_, index)) => {
if *index == i32::max_value() {
-1
} else {
*index as i32
}
}
None => {
-1
}
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn test_0() {
assert_eq!(Solution::first_uniq_char(String::from("leetcode")), 0);
}
#[test]
fn test_1() {
assert_eq!(Solution::first_uniq_char(String::from("loveleetcode")), 2);
}
#[test]
fn test_2() {
assert_eq!(Solution::first_uniq_char(String::from("aadadaad")), -1);
}
}