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.
public class Solution {
    Map<Character, Integer> dict = new HashMap<>();
    public boolean canPermutePalindrome(String s) {
        for(int i=0; i<s.length();i++){
            char ch = s.charAt(i);
            if(dict.containsKey(ch)){
                dict.put(ch, dict.get(ch)+1);
            }else{
                dict.put(ch, 1);
            }
        }
        int oddCount = 0;
        for(Character ch : dict.keySet()){
            int count = dict.get(ch);
            if((count%2) == 1) oddCount++;
        }
        if(oddCount>1) return false;
        else return true;
    }
}

you don't really need to count.

public 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 s.length() %2 == 1 ? set.size() == 1 : set.size() == 0;
    }
}

results matching ""

    No results matching ""