commit 5a6cba4d25e6bf80c57aa0b65778a947a0d940f1
parent c6b7c4bdc62e1b77f2f4ae405fdeb8f9fbdfa91d
Author: Jack Sangdahl <jack@pngu.org>
Date: Tue, 4 Feb 2025 22:31:36 -0700
1790. check if one string swap can make strings equal
Diffstat:
2 files changed, 59 insertions(+), 0 deletions(-)
diff --git a/check_string_swap_eq.c b/check_string_swap_eq.c
@@ -0,0 +1,32 @@
+// 1790. Check if One String Swap Can Make Strings Equal
+#include "leetcode.h"
+
+/*
+ * you are given two strings 's1' and 's2' of equal length. a string swap is an
+ * operation where you choose two indices in a string (not necessarily
+ * different) and swap the characters at these indices. return 'true' if it is
+ * possible to make both strings equal by performing at most one string swap on
+ * exactly one of the strings. otherwise, return 'false'.
+ */
+
+bool areAlmostEqual(char *s1, char *s2) {
+ int n = strlen(s1), cnt = 0, idx1 = 0, idx2 = 0;
+ for (int i = 0; i < n; i++)
+ if (s1[i] != s2[i]) {
+ cnt++;
+ if (!idx1)
+ idx1 = i;
+ else
+ idx2 = i;
+ }
+ return (!cnt || cnt == 2) && s1[idx1] == s2[idx2] && s1[idx2] == s2[idx1];
+}
+
+int main() {
+ char *s11 = "bank", *s21 = "kanb";
+ char *s12 = "attack", *s22 = "defend";
+ char *s13 = "kelb", *s23 = "kelb";
+ printf("%d\n", areAlmostEqual(s11, s21)); // expect: 1
+ printf("%d\n", areAlmostEqual(s12, s22)); // expect: 0
+ printf("%d\n", areAlmostEqual(s13, s23)); // expect: 1
+}
diff --git a/check_string_swap_eq.py b/check_string_swap_eq.py
@@ -0,0 +1,27 @@
+# 1790. Check if One String Swap Can Make Strings Equal
+
+"""
+you are given two strings 's1' and 's2' of equal length. a string swap is an
+operation where you choose two indices in a string (not necessarily
+different) and swap the characters at these indices. return 'true' if it is
+possible to make both strings equal by performing at most one string swap on
+exactly one of the strings. otherwise, return 'false'.
+"""
+
+
+class Solution(object):
+ def areAlmostEqual(self, s1, s2):
+ """
+ :type s1: str
+ :type s2: str
+ :rtype: bool
+ """
+ diff = [[x, y] for x, y in zip(s1, s2) if x != y]
+ return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.areAlmostEqual(s1="bank", s2="kanb"))
+ print(obj.areAlmostEqual(s1="attack", s2="defend"))
+ print(obj.areAlmostEqual(s1="kelb", s2="kelb"))