Today’s problem
https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/description
Intuition
Do what the question ask.
Approach
Do what the question ask.
- Check that whether there are 0 or exactly 2 position that is different.
- Check that whether swapping can solve the question.
Complexity
-
Time complexity: $O(N)$, N is the length of the string.
-
Space complexity: $O(1)$.
Code
class Solution:
def areAlmostEqual(self, s1: str, s2: str) -> bool:
fst = -1
sec = -1
for i in range(len(s1)):
if s1[i] != s2[i]:
if fst == -1:
fst = i
elif sec == -1:
sec = i
else:
return False
if fst == -1 and sec == -1:
return True
if fst == -1 or sec == -1:
return False
if s1[fst] == s2[sec] and s1[sec] == s2[fst]:
return True
return False
