first-unique-character-in-a-string
This commit is contained in:
parent
1ff27f159a
commit
32c5f971c6
|
@ -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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue