[Leetcode] Palindrome Permutation 回文变换

Palindrome Permutation

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?

哈希表法

复杂度

时间 O(N) 空间 O(N)

思路

Leetcode的提示其实已经将答案告诉我们了。最笨的方法就是用Permutations的解法,找出所有的Permutation,然后再用Palindrome中判断回文的方法来判断结果中是否有回文。但是我们考察一下回文的性质,回文中除了中心对称点的字符,其他字符都会出现偶数次。而中心对称点如果是字符,该字符会是奇数次,如果在两个字符之间,则所有字符都是出现偶数次。所以,我们只要判断下字符串中每个字符出现的次数,就知道该字符串的其他排列方式中是否有回文了。

注意

  • 本题也可以用一个HashSet,第偶数个字符可以抵消Set中的字符,最后判断Set的大小是否小于等于1就行了。

代码

HashMap实现

public class Solution {
    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;
    }
}

HashSet实现

public class Solution {
    public boolean canPermutePalindrome(String s) {
        Set<Character> set = new HashSet<Character>();
        for(int i = 0; i < s.length(); i++){
            // 出现的第偶数次,将其从Set中移出
            if(set.contains(s.charAt(i))){
                set.remove(s.charAt(i));
            } else {
            // 出现的第奇数次,将其加入Set中
                set.add(s.charAt(i));
            }
        }
        // 最多只能有一个奇数次字符
        return set.size() <= 1;
    }
}
    原文作者:ethannnli
    原文地址: https://segmentfault.com/a/1190000003790181
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞