JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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

Code

class Solution {
    public boolean canPermutePalindrome(String s) {
        int[] dict = new int[26];

        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            dict[c - 'a']++;
        }

        boolean odd = false;
        for(int num : dict) {
            if(num % 2 == 0) continue;
            if(odd == true) return false;
            odd = true;
        }

        return true;
    }
}
class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        d = defaultdict(int)

        for c in s:
            index = ord(c) - ord('a')
            d[index] += 1

        odd = 0
        for key in d:
            if d[key] % 2 == 1:
                odd += 1

        return True if odd <= 1 else False