Algorithm/Leet Code
[LeetCode/Python] 859. Buddy Strings
byolee
2020. 7. 12. 01:14
859. Buddy Strings
Easy
Given two strings A and B of lowercase letters, return true
if and only if we can swap two letters in A so that the result equals B.
class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B) : return False
elif A == B :
setA = list(set(list(A)))
if len(setA) < len(A) : return True
else : return False
diff = []
for i in range(len(A)) :
if A[i] != B[i] :
if len(diff) == 2 : return False
else : diff.append(i)
if len(diff) < 2 : return False
listA = list(A)
temp = listA[diff[0]]
listA[diff[0]] = listA[diff[1]]
listA[diff[1]] = temp
return ''.join(listA) == B
A와 B의 길이가 다르면 무조건 False 리턴
A와 B가 같을 때는 적어도 한 문자가 2개 이상이 있어야 하므로 집합일 때의 길이와 문자열의 길이를 비교해서 True, False 리턴
한 개씩 순회하면서 문자가 다른 경우에는 인덱스를 diff에 담는데 diff가 2를 초과하게 될 때, 2보다 작을 때 False 리턴
2일 때는 두 문자를 SWAP해서 B와 같은지 비교한 것을 리턴한다.
https://leetcode.com/problems/buddy-strings/
Buddy Strings - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com