diff options
author | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
---|---|---|
committer | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
commit | 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch) | |
tree | 0072cca328fe5adb2ed61004010228ff85e2164d /buddy-strings/src/main.rs |
Diffstat (limited to 'buddy-strings/src/main.rs')
-rw-r--r-- | buddy-strings/src/main.rs | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/buddy-strings/src/main.rs b/buddy-strings/src/main.rs new file mode 100644 index 0000000..dbc982c --- /dev/null +++ b/buddy-strings/src/main.rs @@ -0,0 +1,31 @@ +fn main() { + println!("Hello, world!"); + let tests = [ + ("ab", "ba", true), + ("ab", "ab", false), + ("aa", "aa", true), + ("abcaa", "abcbb", false) + ]; + + for test in tests { + println!("{:?} {:?} is {} should be {}", test.0, test.1, + Solution::buddy_strings(test.0.clone().to_string(), test.1.clone().to_string()), + test.2); + } +} +struct Solution; + +use std::collections::HashMap; + +impl Solution { + pub fn buddy_strings(s: String, goal: String) -> bool { + let mut occurences_s = HashMap::new(); + let mut occurences_goal = HashMap::new(); + let similarities = s.chars().zip(goal.chars()).filter(|(a,b)| { + *occurences_s.entry(a.clone()).or_insert(1) += 1; + *occurences_goal.entry(b.clone()).or_insert(1) += 1; + a != b}) + .count(); + s.len() == goal.len() && occurences_s == occurences_goal && (similarities == 2 || (similarities == 0 && occurences_s.values().any(|&x| x > 2))) + } +} |