1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-10-29 22:17:23 +01:00

feat(solutions): add first-non-repeating-character/rust/function

This commit is contained in:
Divlo 2023-01-05 19:01:25 +01:00
parent 1553324b3a
commit 1a12e0db0c
No known key found for this signature in database
GPG Key ID: 8F9478F220CE65E9
4 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "rust_application"
version = "1.0.0"

View File

@ -0,0 +1,6 @@
[package]
name = "rust_application"
version = "1.0.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,3 @@
# first-non-repeating-character/rust/function
Created by [@Divlo](https://github.com/Divlo) on 5 January 2023.

View File

@ -0,0 +1,63 @@
use std::{collections::HashMap, io};
#[derive(Debug, Copy, Clone)]
pub struct CharacterOccurence {
pub total: usize,
pub first_index: usize,
pub value: char,
}
pub fn first_non_repeating_character(string: &str) -> String {
let mut characters_occurences: HashMap<char, CharacterOccurence> = HashMap::new();
for (index, character) in string.chars().enumerate() {
match characters_occurences.get(&character) {
Some(value) => {
characters_occurences.insert(
character,
CharacterOccurence {
total: value.total + 1,
..value.clone()
},
);
}
None => {
characters_occurences.insert(
character,
CharacterOccurence {
total: 1,
first_index: index,
value: character,
},
);
}
}
}
let mut result: Option<CharacterOccurence> = Option::None;
for (_, character_occurence) in &characters_occurences {
if character_occurence.total == 1 {
match result {
Some(ref mut result) => {
if character_occurence.first_index < result.first_index {
*result = *character_occurence;
}
}
None => {
result = Some(*character_occurence);
}
}
}
}
match result {
Some(result) => result.value.to_string(),
None => "".to_string(),
}
}
fn main() {
let mut string = String::new();
io::stdin()
.read_line(&mut string)
.expect("Failed to read `stdin` line.");
let string = string.trim();
println!("{}", first_non_repeating_character(&string));
}