266. Palindrome Permutation

2019/10/23 Leetcode

266. Palindrome Permutation

Tags: ‘Hash Table’

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

65% 100%

public boolean canPermutePalindrome(String s) {
    // have at most 1 single char
    Map<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (map.containsKey(c)) {
            map.put(c, map.get(c) + 1);
        } else {
            map.put(c, 1);
        }
    }
    
    int count = 0;
    for (Integer i: map.values()) {
        if (i % 2 != 0) {
            count++;
        }
    }
    return count <= 1;
}

Search

    Table of Contents