Palindrome Permutation
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False,"aab"
-> True,"carerac"
-> True.
A better solution is suggested from the above hint.
If each character occurs even numbers, then a permutation of the string could form a palindrome.
If only one character occurs odd number of times, it can also form a palindrome. like
aba, abbba.
1. 这道题让我们判断一个字符串的全排列有没有是回文字符串的,那么根据题目中的提示,我们分字符串的个数是奇偶的情况来讨论,如果是偶数的话,由于回文字符串的特性,每个字母出现的次数一定是偶数次,当字符串是奇数长度时,只有一个字母出现的次数是奇数,其余均为偶数,那么利用这个特性我们就可以解题,我们建立每个字母和其出现次数的映射,然后我们遍历 HashMap,统计出现次数为奇数的字母的个数,那么只有两种情况是回文数,第一种是没有出现次数为奇数的字母,再一个就是字符串长度为奇数,且只有一个出现次数为奇数的字母
2. hashset
那么我们再来看一种解法,这种方法用到了一个 HashSet,我们遍历字符串,如果某个字母不在 HashSet 中,我们加入这个字母,如果字母已经存在,我们删除该字母,那么最终如果 HashSet 中没有字母或是只有一个字母时,说明是回文串
We can use a HashTable to count the frequency of the charactersin the string. A better one is to use a HashSet, if a character is in the HashSet, and we see it again, we remove it from the HashSet. This means the character occurs even times. At the end, There are two valid possibilities:
The HashSet is empty, which means all the characters occur even times, returning true;
The HashSet contains only one character, which means only one character occurs odd times. returning true.
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
hashset = set()
for item in s:
if item in hashset:
hashset.remove(item)
else:
hashset.add(item)
return len(hashset) <= 1
2. 还可以用xor
Last updated
Was this helpful?