[LeetCode] 409. Longest Palindrome

2022. 9. 26. 00:23·코딩테스트/Python
728x90
반응형

🔗 Problem Link

 

Longest Palindrome - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


❔Thinking

  • 주어진 문자열의 문자들로 만들 수 있는 가장 긴 '펠린드롬 문자열'의 길이를 출력한다.
  • '펠린드롬 문자열'은 가운데를 기준으로 좌우를 뒤집어도 동일한 문자열을 말한다.
  • 모든 문자를 사용하지 않아도 된다.

💻Solution

from collections import Counter
class Solution:
    def longestPalindrome(self, s: str) -> int:
        s_letter_cnt = Counter(s).values()
        palindrom_cnt, flag = 0, False
        for cnt in s_letter_cnt:
            if cnt % 2 == 0:
                palindrom_cnt += cnt
            else:
                flag = True
                palindrom_cnt += cnt-1
        return palindrom_cnt if flag is False else palindrom_cnt+1

🗝️keypoint

  1. 모든 문자를 사용한다면, 짝수개의 알파벳은 다 더하고 홀수개의 알파벳 중 가장 긴 알파벳만 더한다. 
  2. flag를 사용하여 특정 조건의 발생 여부를 판단할 수 있다.
  3. Counter(문자열)은 각 문자를 key로 하고 그 개수를 value로 하는 dictionary를 반환한다. (단, type은 counter이다)

'코딩테스트 > Python' 카테고리의 다른 글

[Baekjoon] 1439번 - 뒤집기  (0) 2022.09.27
[Programmers] Level 2. 모음사전  (0) 2022.09.27
[Programmers] Level 2. 파일명 정렬  (1) 2022.09.27
[Programmers] Level 2. 땅따먹기  (0) 2022.09.25
[Programmers] Level 2. 방문 길이  (0) 2022.09.25
'코딩테스트/Python' 카테고리의 다른 글
  • [Programmers] Level 2. 모음사전
  • [Programmers] Level 2. 파일명 정렬
  • [Programmers] Level 2. 땅따먹기
  • [Programmers] Level 2. 방문 길이
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[LeetCode] 409. Longest Palindrome
상단으로

티스토리툴바