본문 바로가기
Leetcode

[LeetCode] Find the Difference 파이썬 (Counter, A.subtract(B), bit operation, xor, reduce)

by YGSEO 2021. 4. 14.
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

댓글