leet-code/first-unique-character-in-a.../sol.rs

19 lines
686 B
Rust
Raw Permalink Normal View History

2022-06-02 22:43:47 +00:00
impl Solution {
pub fn first_uniq_char(s: String) -> i32 {
let (earliest_index, counts) = s.bytes()
.enumerate()
.fold(([-1; 26], [0; 26]), |(mut earliest_index, mut counts), (idx, chr)| {
if earliest_index[chr as usize - 97] == -1 {
earliest_index[chr as usize - 97] = idx as i32;
}
counts[chr as usize - 97] += 1;
(earliest_index, counts)
});
s.bytes().find_map(|chr| {
if counts[chr as usize - 97] == 1 {
return Some(earliest_index[chr as usize - 97])
}
None
}).unwrap_or(-1)
}
}