summaryrefslogtreecommitdiff
path: root/buddy-strings
diff options
context:
space:
mode:
authorOrangerot <purple@orangerot.dev>2024-06-27 11:30:16 +0200
committerOrangerot <purple@orangerot.dev>2024-06-27 11:30:16 +0200
commit4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch)
tree0072cca328fe5adb2ed61004010228ff85e2164d /buddy-strings
Initial commitHEADmain
Diffstat (limited to 'buddy-strings')
-rw-r--r--buddy-strings/Cargo.toml8
-rw-r--r--buddy-strings/src/main.rs31
2 files changed, 39 insertions, 0 deletions
diff --git a/buddy-strings/Cargo.toml b/buddy-strings/Cargo.toml
new file mode 100644
index 0000000..c7ee668
--- /dev/null
+++ b/buddy-strings/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "buddy-strings"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
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)))
+ }
+}