From 61dcce1a7601d238943d43351df3aab87f52bee6 Mon Sep 17 00:00:00 2001 From: Bauke Date: Sat, 9 Apr 2022 20:25:08 +0200 Subject: [PATCH] Solve isomorphic-strings. --- source/isomorphic_strings/mod.rs | 15 +++++++++++++++ source/lib.rs | 1 + tests/isomorphic_strings.rs | 11 +++++++++++ 3 files changed, 27 insertions(+) create mode 100644 source/isomorphic_strings/mod.rs create mode 100644 tests/isomorphic_strings.rs diff --git a/source/isomorphic_strings/mod.rs b/source/isomorphic_strings/mod.rs new file mode 100644 index 0000000..41599e7 --- /dev/null +++ b/source/isomorphic_strings/mod.rs @@ -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 +} diff --git a/source/lib.rs b/source/lib.rs index 1814c68..5b9f1b4 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -2,6 +2,7 @@ pub mod add_binary; pub mod excel_sheet_column_number; pub mod excel_sheet_column_title; pub mod implement_strstr; +pub mod isomorphic_strings; pub mod length_of_last_word; pub mod longest_common_prefix; pub mod missing_number; diff --git a/tests/isomorphic_strings.rs b/tests/isomorphic_strings.rs new file mode 100644 index 0000000..9d3c4bb --- /dev/null +++ b/tests/isomorphic_strings.rs @@ -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); +}