Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
- 如果
len(s) % 2 = 0
, 那么每个元素必须成对出现。如果len(s) % 2 = 1
, 那么除了一个元素数量为奇数外,其他的必须为偶数。
from collections import Counter
class Solution:
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
c = Counter(s)
if len(s) % 2 == 0:
return sum(map(lambda c: c % 2 == 1, c.values())) == 0
return sum(map(lambda c: c % 2 == 1, c.values())) == 1