물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

266. Palindrome Permutation

BEstyle 2023. 3. 28. 18:57

Given a string s, return true if a permutation of the string could form a 

palindrome

 and false otherwise.

 

Example 1:

Input: s = "code"
Output: false

Example 2:

Input: s = "aab"
Output: true

Example 3:

Input: s = "carerac"
Output: true

 

Constraints:

  • 1 <= s.length <= 5000
  • s consists of only lowercase English letters.

class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        if len(s)<=1:
            return True
    
        isodd=len(s)%2
        c={}
        for char in s:
            if char not in c:
                c[char]=1
            else:
                c[char]+=1
        if len(c)<=1:
            return True
        
        if isodd:
            count=0
            for k,v in c.items():
                if v%2==1:
                    count+=1
            return count==1
        else:
            for k,v in c.items():
                if v%2==1:
                    return False
        return True