859. Buddy Strings
Problem¶
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 at indices
0and2in"abcd"results in"cbad".
Constraints:
1 <= s.length, goal.length <= 2 * 10**4sandgoalconsist of lowercase letters.
Solve¶
Read the problem¶
- Only one swap is allow, and we get two identical string
Analysis¶
- The constrain is really low
- There should be two case that return
True, which is: 1. Stringsandgoalhave no different, we swap an identical character so the string remain unchanged; 2. Stringsandgoalhave a pair(x,y)being swap
Code it¶
- Just a regular loop through all character of
pair(s, goal)check to find if there is any different character. Storing their position indiffarray - If
len(s) > len(goal)orlen(diff) != 0 and len(diff) != 2then we can just returnFalse - For case 1.
len(diff) == 0we can loop through stringsand find if any character is repeat (usingset()to keep track which char have show up). ReturnTrueif found orFalseif not - For case 2.
len(diff) == 2we can quick check if swapping 2 character with positiondiff[0], diff[1]of eithersorgoalis equal to the other one or not: Usings[diff[1]] == goal[diff[0]] and s[diff[0]] == goal[diff[1]]
Implement¶
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
# Find different of s and goal
if len(s) != len(goal):
return False
diff = []
for i, (x, y) in enumerate(zip(s, goal)):
if x != y:
diff.append(i)
if len(diff) != 0 and len(diff) != 2:
return False
if len(diff) == 2:
return s[diff[1]] == goal[diff[0]] and s[diff[0]] == goal[diff[1]]
check = set()
for c in s:
if c not in check:
check.add(c)
else:
return True
return False
Last update :
October 13, 2023
Created : August 16, 2023
Created : August 16, 2023