first-unique-character-in-a-string

This commit is contained in:
Gleb Koval 2022-06-02 23:43:47 +01:00
parent 1ff27f159a
commit 32c5f971c6
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 19 additions and 0 deletions

View File

@ -0,0 +1,19 @@
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)
}
}