Skip to content

Instantly share code, notes, and snippets.

@Nyrox
Created March 27, 2018 08:40
Show Gist options
  • Save Nyrox/cf0fec8d0159e46ed26f9f61cbb47892 to your computer and use it in GitHub Desktop.
Save Nyrox/cf0fec8d0159e46ed26f9f61cbb47892 to your computer and use it in GitHub Desktop.
/*
Given two strings, find the number of common characters between them.
Example
For s1 = "aabcc" and s2 = "adcaa", the output should be
commonCharacterCount(s1, s2) = 3.
Strings have 3 common characters - 2 "a"s and 1 "c".
*/
use std::collections::HashMap;
fn commonCharacterCount(s1: String, s2: String) -> i32 {
let mut charCounts = (HashMap::new(), HashMap::new());
populate_hashmap(&mut charCounts.0, &s1);
populate_hashmap(&mut charCounts.1, &s2);
let mut n = 0;
// I am not allowed to use inclusive range syntax on codefights ;(
for i in ('a' as u8)..('z' as u8) + 1 {
n += i32::min(
*charCounts.0.entry(i as char).or_insert(0),
*charCounts.1.entry(i as char).or_insert(0)
);
}
return n;
}
fn populate_hashmap(map: &mut HashMap<char, i32>, string: &str) {
for c in string.chars() {
let count = map.entry(c).or_insert(0);
*count += 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment