aboutsummaryrefslogtreecommitdiff
path: root/other/buddy_strings.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/buddy_strings.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/buddy_strings.cpp')
-rw-r--r--other/buddy_strings.cpp46
1 files changed, 46 insertions, 0 deletions
diff --git a/other/buddy_strings.cpp b/other/buddy_strings.cpp
new file mode 100644
index 0000000..22ce6d8
--- /dev/null
+++ b/other/buddy_strings.cpp
@@ -0,0 +1,46 @@
+// 859. Buddy Strings
+#include "leetcode.h"
+
+/*
+ * given two strings 's' and 'goal', return 'true' if you can swap two letters
+ * in 's' so the result is equal to 'goal', otherwise, return 'false'. swapping
+ * letters is defined as taking two indices 'i' and 'j' 0-indexed such that 'i
+ * != j' and swapping the characters at 's[i]' and 's[j]'. for example, swapping
+ * indices at '0' and '2' in "abcd" results in "cbad"
+ */
+
+class Solution {
+public:
+ bool buddyStrings(string s, string goal) {
+ if (s.size() != goal.size())
+ return false;
+ if (s == goal) {
+ unordered_map<char, int> cnt;
+ for (auto i : s) {
+ cnt[i]++;
+ if (cnt[i] > 1)
+ return true;
+ }
+ return false;
+ }
+ vector<int> diff;
+ for (int i = 0; i < s.size(); i++)
+ if (s[i] != goal[i]) {
+ diff.push_back(i);
+ if (diff.size() > 2)
+ return false;
+ }
+ if (diff.size() != 2)
+ return false;
+ if ((s[diff[0]] == goal[diff[1]]) && (s[diff[1]] == goal[diff[0]]))
+ return true;
+ return false;
+ }
+};
+
+int main() {
+ Solution obj;
+ printf("%d\n", obj.buddyStrings("ab", "ba")); // expect: 1
+ printf("%d\n", obj.buddyStrings("ab", "ab")); // expect: 0
+ printf("%d\n", obj.buddyStrings("aa", "aa")); // expect: 1
+}