1
Fork 0

Solve isomorphic-strings.

This commit is contained in:
Bauke 2022-04-09 20:25:08 +02:00
parent 2c193f140d
commit 61dcce1a76
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
3 changed files with 27 additions and 0 deletions

View File

@ -0,0 +1,15 @@
pub fn is_isomorphic(a: String, b: String) -> bool {
let mut map_a = std::collections::HashMap::new();
let mut map_b = std::collections::HashMap::new();
for (a, b) in a.chars().zip(b.chars()) {
let from_map_a = *map_a.entry(a).or_insert(b);
let from_map_b = *map_b.entry(b).or_insert(a);
if from_map_b != a || from_map_a != b {
return false;
}
}
true
}

View File

@ -2,6 +2,7 @@ pub mod add_binary;
pub mod excel_sheet_column_number; pub mod excel_sheet_column_number;
pub mod excel_sheet_column_title; pub mod excel_sheet_column_title;
pub mod implement_strstr; pub mod implement_strstr;
pub mod isomorphic_strings;
pub mod length_of_last_word; pub mod length_of_last_word;
pub mod longest_common_prefix; pub mod longest_common_prefix;
pub mod missing_number; pub mod missing_number;

View File

@ -0,0 +1,11 @@
use leetcode::isomorphic_strings::is_isomorphic;
use test_case::test_case;
#[test_case("egg", "add", true; "valid")]
#[test_case("foo", "bar", false; "invalid")]
#[test_case("badc", "baba", false; "map both ways")]
#[test_case("paper", "title", true; "different maps")]
fn test_isomorphic_strings(a: &str, b: &str, expected: bool) {
assert_eq!(is_isomorphic(a.to_string(), b.to_string()), expected);
}