From 32c5f971c694081262245fd850467787d9f6bd1a Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Thu, 2 Jun 2022 23:43:47 +0100 Subject: [PATCH] first-unique-character-in-a-string --- first-unique-character-in-a-string/sol.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 first-unique-character-in-a-string/sol.rs diff --git a/first-unique-character-in-a-string/sol.rs b/first-unique-character-in-a-string/sol.rs new file mode 100644 index 0000000..a11ea89 --- /dev/null +++ b/first-unique-character-in-a-string/sol.rs @@ -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) + } +} \ No newline at end of file