Skip to content

Latest commit

 

History

History
107 lines (82 loc) · 2.04 KB

File metadata and controls

107 lines (82 loc) · 2.04 KB

中文文档

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.

Solutions

Python3

class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        counter = Counter(s)
        return sum(e % 2 for e in counter.values()) < 2

Java

class Solution {
    public boolean canPermutePalindrome(String s) {
        Map<Character, Integer> counter = new HashMap<>();
        for (char c : s.toCharArray()) {
            counter.put(c, counter.getOrDefault(c, 0) + 1);
        }
        int oddCnt = 0;
        for (int e : counter.values()) {
            oddCnt += e % 2;
        }
        return oddCnt < 2;
    }
}

C++

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> counter;
        for (char c : s) ++counter[c];
        int oddCnt = 0;
        for (auto& it : counter) oddCnt += it.second % 2;
        return oddCnt < 2;
    }
};

Go

func canPermutePalindrome(s string) bool {
    counter := make(map[rune]int)
    for _, c := range s {
        counter[c]++
    }
    oddCnt := 0
    for _, e := range counter {
        oddCnt += e % 2
    }
    return oddCnt < 2
}

...