Problem

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

Example 1:

Input: "code"
Output: false
Example 2:

Input: "aab"
Output: true
Example 3:

Input: "carerac"
Output: true

Solution

class Solution {
    public boolean canPermutePalindrome(String s) {
        Set<Character> set = new HashSet<>();
        for (char ch: s.toCharArray()) {
            if (set.contains(ch)) set.remove(ch);
            else set.add(ch);
        }
        return set.size() <= 1;
    }
}

linspiration
161 声望53 粉丝