Given a string, determine if a permutation of the string could form a palindrome.
For example,"code"
-> False, "aab"
-> True, "carerac"
-> True.
Hint:
- Consider the palindromes of odd vs even length. What difference do you notice?
- Count the frequency of each character.
- If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
解题思路:
permutation 排列, palindrome 回文 判断一个string 能否组合成一个回文。思路参考Hint.
我用了HashMap, 计算如果character 的数目是odd, 最多只有一个时,为真。但从discussion中发现,有人的方法更巧妙,复杂度更低。贴过来参考。
还有一种方法,用HashSet.
Java code:
my code:(use map)
public boolean canPermutePalindrome(String s) { Map<Character, Integer> x = new HashMap<Character, Integer>(); for(int i = 0; i< s.length(); i++){ if(x.containsKey(s.charAt(i))){ x.put(s.charAt(i), x.get(s.charAt(i))+1); }else{ x.put(s.charAt(i), 1); } } int odd = 0; for(Character key: x.keySet()){ int number = x.get(key); if(number % 2 == 1) { odd++; } } if(odd == 0 || odd == 1){ return true; } return false; }
better code:(use map)
public boolean canPermutePalindrome(String s) { Map<Character, Integer> x = new HashMap<Character, Integer>(); for(int i = 0; i< s.length(); i++){ if(x.containsKey(s.charAt(i))){ x.remove(s.charAt(i)); }else{ x.put(s.charAt(i), 1); } } if(x.size() > 1) { return false; } return true; }
better code: (use set)
public boolean canPermutePalindrome(String s) { Set<Character> set = new HashSet<Character>(); for(int i = 0; i< s.length(); i++){ if(set.contains(s.charAt(i))){ set.remove(s.charAt(i)); }else { set.add(s.charAt(i)); } } if(set.size() == 0 || set.size() == 1){ return true; } return false; }
Reference:
1. https://leetcode.com/discuss/53295/java-solution-w-set-one-pass-without-counters
2. https://leetcode.com/discuss/53472/simple-java-solution