266. Palindrome Permutation

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    public boolean canPermutePalindrome(String s) {
        int[] freq = new int[256];
        for (char c: s.toCharArray()) {
            freq[c]++;
        }
        int count = 0;
        for (int f: freq) {
            count += f % 2;
        }
        return count <= 1;
    }
}