美文网首页
266. Palindrome Permutation

266. Palindrome Permutation

作者: Nancyberry | 来源:发表于2018-05-23 23:25 被阅读0次

Description

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

HashMap, O(n), S(n)

class Solution {
    public boolean canPermutePalindrome(String s) {
        if (s == null) {
            return false;
        }
        
        Map<Character, Integer> freq = new HashMap<>();
        int len = s.length();
        for (int i = 0; i < len; ++i) {
            char c = s.charAt(i);
            freq.put(c, 1 + freq.getOrDefault(c, 0));
        }
        
        int oddCount = 0;
        for (int count : freq.values()) {
            if (count % 2 > 0) {
                ++oddCount;
            }
        }
        
        return (len % 2 == 0 && oddCount == 0) 
            || (len % 2 > 0 && oddCount == 1);
    }
}

相关文章

网友评论

      本文标题:266. Palindrome Permutation

      本文链接:https://www.haomeiwen.com/subject/hdzdjftx.html