题目:
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?
链接: http://leetcode.com/problems/palindrome-permutation/
3/5/2017
要学会几种遍历hashmap的方法。
1 public class Solution { 2 public boolean canPermutePalindrome(String s) { 3 HashMap<Character, Integer> h = new HashMap<Character, Integer>(); 4 5 for(int i = 0; i < s.length(); i++) { 6 if (h.containsKey(s.charAt(i))) h.put(s.charAt(i), h.get(s.charAt(i)) + 1); 7 else h.put(s.charAt(i), 1); 8 } 9 int oddCount = 0; 10 boolean isEvenLength = (s.length() % 2 == 0); 11 for (HashMap.Entry<Character, Integer> entry: h.entrySet()) { 12 if (entry.getValue() % 2 != 0) { 13 if (isEvenLength) return false; 14 else oddCount++; 15 } 16 } 17 return oddCount <= 1; 18 } 19 }