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

For example, "code" -> False, "aab" -> True, "carerac" -> True.

Hint:

Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

Solution

public class Solution {
    public boolean canPermutePalindrome(String s) {
        int count[] = new int[130];
        int odd = 0;
        for(int i = 0; i < s.length(); i++) {
            if(count[s.charAt(i)]++ % 2 == 0) odd++;
            else odd--;
        }
        return odd <= 1;
    }
}

results matching ""

    No results matching ""