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?
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 if (s==null || s.length()==0) return true; 4 int[] count = new int[256]; 5 for (int i=0; i<s.length(); i++) { 6 char c = s.charAt(i); 7 count[(int)(c - ' ')]++; 8 } 9 int countOdd = 0; 10 for (int i=0; i<256; i++) { 11 if (count[i]%2 == 1) countOdd++; 12 } 13 if (s.length()%2==0 && countOdd==0) return true; 14 if (s.length()%2==1 && countOdd==1) return true; 15 return false; 16 } 17 }