Palindrome Permutation
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
那么我们再来看一种解法,这种方法用到了一个 HashSet,我们遍历字符串,如果某个字母不在 HashSet 中,我们加入这个字母,如果字母已经存在,我们删除该字母,那么最终如果 HashSet 中没有字母或是只有一个字母时,说明是回文串
We can use a to in 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.