본문 바로가기
Leetcode

[LeetCode] Longest Palindrome 파이썬 (bitwise &, Counter)

by YGSEO 2021. 4. 16.
728x90
from collections import Counter


class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: int
        """
        odds = 0
        for k, v in Counter(s).items():
            odds += v & 1
        return len(s) - odds + int(odds > 0)

lambda, map을 사용해서 홀 수 인 s 구하기

def longestPalindrome2(self, s):
        """
        :type s: str
        :rtype: int
        """
        odd = sum(map(lambda x: x & 1, Counter(s).values()))
        return len(s) - odd + int(odd > 0)

홀수개의 str 여부를 파악하는 이유는

palindrome을 만들기 위해서는 무조건 짝수 개의 str이 있어야한다.

또한, 짝수개의 str이 있는 상황에서 홀수개의 str중 하나만 사용한다면

parlindrome 구성 조건이 충족된다.

 

따라서 홀수인 str 개수를 구하는 것이다.

 

for 문에서 & 연산으로 홀수 여부를 판단한다.

 

return 에서는

전체 s의 길이 - 홀수인 s의 개수 + (홀수인 s가 있다면 +1) 로 입력해준다.

 


& 1 으로 홀 수 여부 판단.

 

비트 연산으로 & 1 해주면

num % 2 != 0 보다 간편하게 홀수 여부를 판단할 수 있다.

 

 

 

 

 

 

https://www.geeksforgeeks.org/check-if-a-number-is-odd-or-even-using-bitwise-operators/


출처: github.com/jiapengwen/LeetCode/blob/master/Python/longest-palindrome.py

 

 

 

728x90

댓글