-
Leetcode 859. Buddy Strings개발/Leetcode 2023. 7. 3. 10:48
https://leetcode.com/problems/buddy-strings/
Buddy Strings - LeetCode
Can you solve this real interview question? Buddy Strings - 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-ind
leetcode.com
문제
문자열 s와 goal이 주어진다. 이때 s의 문자 중 하나만 바꿔 goal과 같아진다면 True를 반환하고 그렇지 않다면 False를 반환하라
문자를 교환할 때에는 2개의 인덱스를 교환해야 하며 이 때 각 인덱스 i와 j는 같을 수 없다
코드
class Solution:def buddyStrings(self, s: str, goal: str) -> bool:if len(s) != len(goal):return Falsec = 0s_cc = {}g_cc = {}for i in range(len(s)):if s[i] not in s_cc:s_cc[s[i]] = 0if goal[i] not in g_cc:g_cc[goal[i]] = 0
if s[i] != goal[i]:c +=1
s_cc[s[i]] += 1g_cc[goal[i]] += 1for k, v in s_cc.items():if k in g_cc and g_cc[k] == v:passelse:return False
return True if (c == 2 or (c == 0 and max(g_cc.values()) >= 2)) else False
코드가 지저분해서 간단하게 설명하면, s와 goal에서 등장하는 문자를 카운트와 다른 부분의 개수를 확인한다. 그리고 나서 문자를 스왑을 한다고해도 문자의 개수는 같아야 하는 조건 떄문에 각각의 딕셔너리에서 키와 키에 해당하는 값을 비교하고 같지 않다면 False를 반환한다.
이후 다른 부분이 2개라고 한다면 이는 스왑을 통해 같아질 수 있으므로 True를 반환, 그리고 다른 것이 없음에도 불구하고 같은 교환할 수 있는 문자가 2개 이상 있다면 이는 같은 문자를 스왑하는 형식으로 goal 문자열로 바꿀 수 있으므로 True를 반환하는 코드이다.
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 1493. Longest Subarray of 1's After Deleting One Element (0) 2023.07.05 Leetcode 137. Single Number II (0) 2023.07.04 Leetcode 2114. Maximum Number of Words Found in Sentences (0) 2023.07.02 Leetcode 1678. Goal Parser Interpretation (0) 2023.07.02 Leetcode 744. Find Smallest Letter Greater Than Target (0) 2023.07.02