LC 0859 [E] Buddy Strings - ALawliet/algorithms GitHub Wiki
- if length differs or set of characters differ, return False directly
- if A and B are equal, returns if we have at least 1 repetitive character in the list, so we just swap the duplicate
- if two list have more than 2 indices with different characters (more than 2 differences), return False
- In the end check if the swap can happen with the exactly 2 differences because this must be the 2 indices to swap
def buddyStrings(self, A, B):
if len(A) != len(B): return False
if A == B and len(set(A)) < len(A): return True
dif = [(a, b) for a, b in zip(A, B) if a != b]
return len(dif) == 2 and dif[0] == dif[1][::-1]
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
# check same length
if len(A) != len(B): return False
# if strings are equal - check if there is a double to swap
if A == B:
return True if len(A) - len(set(A)) >= 1 else False
# count differences between strings
diff = []
for i in range(len(A)):
if A[i] != B[i]:
diff.append(i)
if len(diff) > 2: return False
# not exactly two differences
if len(diff) != 2: return False
# check if can be swapped
if A[diff[0]] == B[diff[1]] and A[diff[1]] == B[diff[0]]:
return True
return False
class Solution:
def buddyStrings(self, A, B):
if len(A) != len(B) or set(A) != set(B):
return False
if A == B:
return len(A) - len(set(A)) >= 1
indices = []
counter = 0
for i in range(len(A)):
if A[i] != B[i]:
counter += 1
indices.append(i)
if counter > 2:
return False
return A[indices[0]] == B[indices[1]] and A[indices[1]] == B[indices[0]]