Buddy Strings LeetCode solution in Python

1
# Runtime: 54 ms (Top 48.33%) | Memory: 14.1 MB (Top 96.59%)
2

3
from collections import Counter
4

5

6
class Solution:
7
def buddyStrings(self, s: str, goal: str) -> bool:
8
if len(s) != len(goal):
9
return False
10
diffCharactersCount = 0
11
diffCharactersInS = []
12
diffCharactersInGoal = []
13
for i in range(len(s)):
14
if s[i] != goal[i]:
15
diffCharactersCount += 1
16
diffCharactersInS.append(s[i])
17
diffCharactersInGoal.append(goal[i])
18
if diffCharactersCount == 2:
19
# if there are only 2 different characters, then they should be swappable
20
if (diffCharactersInS[0] == diffCharactersInGoal[1]) and (
21
diffCharactersInS[1] == diffCharactersInGoal[0]
22
):
23
return True
24
return False
25
elif diffCharactersCount == 0:
26
# if there is atleast one repeating character in the string then its possible for swap
27
counts = Counter(s)
28
for k, v in counts.items():
29
if v > 1:
30
return True
31
# if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings
32
return False

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0