【leetcode】266. Palindrome Permutation

原题

Given a string, determine if a permutation of the string could form a palindrome.

For example,
"code" -> False, "aab" -> True, "carerac" -> True.

解析

判断是否可以组成回文
给一个字符串,判断字符串中的字符是否可以组成回文

思路

其实思路都一样,计算字符串中的字符个数;若字符串的字符有偶数个,则每个字符的出现次数需要有偶数次;若字符串的字符有奇数个,则最多只能有一个字符出现过奇数次,其他字符都需要出现偶数次

解法1:利用Map 的key的唯一性

public boolean canPermutePalindromeOther1(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
        }
        int singleCount = 0;
        for (Character c : map.keySet()) {
            if ((map.get(c) & 1) != 0) {
                singleCount++;
            }
            if (singleCount > 1) {
                break;
            }
        }
        return singleCount <= 1;
    }

解法2:利用Set元素的唯一性

public boolean canPermutePalindromeOther2(String s) {
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (!set.add(s.charAt(i))) {
                set.remove(s.charAt(i));
            }
        }
        return set.size() <= 1;
    }
posted @ 2017-07-26 16:50  l.shane  阅读(211)  评论(0编辑  收藏  举报