sy1214ei 님의 블로그

[Leet Code] 409. Longest Palindrome - Python 본문

[Coding]

[Leet Code] 409. Longest Palindrome - Python

sy1214ei 2024. 12. 4. 22:13

https://leetcode.com/problems/longest-palindrome/description/

Level : Easy
Topics : Hash Table | String | Greedy
class Solution:
    def longestPalindrome(self, s: str) -> int:
        # "abccccdd" -> "dccaccd" "dccbccd"
        # 해쉬테이블로 각 char타입의 수를 count 해준다.
        # 각 문자별 저장되어있는 count가 짝수이면 -> length로 모두 사용
        #                      count가 홀수이면 -> count-1만큼 length로 사용
        char_cnt = {}
        for char in s:
            if char in char_cnt:
                char_cnt[char] += 1
            else:
                char_cnt[char] = 1

        length = 0
        odd = False

        for count in char_cnt.values(): ############
            if count%2: # 홀수일때
                length += count - 1
                odd = True
            else: # 짝수일때
                length += count
        if odd:
            length += 1
        
        return length
        
        # Time Complexity : O(n)
        # Space Complexity : O(n)