Palindrome Permutation(Easy)

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?

解题思路:HashMap

但是我们考察一下回文的性质,回文中除了中心对称点的字符,其他字符都会出现偶数次。而中心对称点如果是字符,该字符会是奇数次,如果在两个字符之间,则所有字符都是出现偶数次。所以,我们只要判断下字符串中每个字符出现的次数,就知道该字符串的其他排列方式中是否有回文了。

public boolean canPermutePalindrome(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        // 统计每个字符的个数
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            Integer cnt = map.get(c);
            if(cnt == null){
                cnt = new Integer(0);
            }
            map.put(c, ++cnt);
        }

        // 判断是否只有不大于一个的奇数次字符
        boolean hasOdd = false;
        for(Character c : map.keySet()){
            if(map.get(c) % 2 == 1){
                if(!hasOdd){
                    hasOdd = true;
                } else {
                    return false;
                }
            }
        }
        return true;
}

results matching ""

    No results matching ""