diff options
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))) + } +} |