728x90
from collections import Counter
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
if len(s) == 0:
return t # s = ""
S = Counter(s)
T = Counter(t)
T.subtract(S) # inplace
res = [k for k, v in T.items() if v > 0]
return res[0]
Counter 클래스에는 subtract라는 메서드가 있다.
inplace이기 때문에 이 점을 유의할 것.
다른 풀이들
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0))
def findTheDifference2(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
t = list(t)
s = list(s)
for i in s:
t.remove(i)
return t[0]
def findTheDifference3(self, s, t):
return chr(reduce(operator.xor, map(ord, s + t)))
def findTheDifference4(self, s, t):
return list((collections.Counter(t) - collections.Counter(s)))[0]
def findTheDifference5(self, s, t):
s, t = sorted(s), sorted(t)
return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0]
bit operation에 대한 이해가 아직 부족하다.
멋있어 보이는데
출처: github.com/jiapengwen/LeetCode/blob/master/Python/find-the-difference.py
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Sum of Left Leaves 파이썬 (Tree) (0) | 2021.04.15 |
---|---|
[LeetCode] Is Subsequence 파이썬 (pointer, relative position) (0) | 2021.04.15 |
[LeetCode] First Unique Character in a String 파이썬 (Counter, str.find) (0) | 2021.04.14 |
[LeetCode] Ransom Note 파이썬 (dict, set, count) (0) | 2021.04.14 |
[LeetCode] Guess Number Higher or Lower 파이썬 (binary search) (0) | 2021.04.14 |
댓글