0266. Palindrome Permutation

https://leetcode.com/problems/palindrome-permutation

Description

Given a string s, return true if a permutation of the string could form a palindrome.

Example 1:

**Input:** s = "code"
**Output:** false

Example 2:

**Input:** s = "aab"
**Output:** true

Example 3:

**Input:** s = "carerac"
**Output:** true

Constraints:

  • 1 <= s.length <= 5000

  • s consists of only lowercase English letters.

ac

class Solution {
    public boolean canPermutePalindrome(String s) {
        // edge cases
        if (s.length() <= 1) return true;

        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        boolean oddFound = false;
        for (char k : map.keySet()) {
            int val = map.get(k);
            if (val % 2 == 1) {
                if (oddFound) return false;
                else oddFound = true;
            }
        }

        return true;
    }
}

Last updated