Skip to content

Latest commit

 

History

History
107 lines (82 loc) · 1.95 KB

File metadata and controls

107 lines (82 loc) · 1.95 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) {
        int[] counter = new int[26];
        for (char c : s.toCharArray()) {
            ++counter[c - 'a'];
        }
        int oddCnt = 0;
        for (int cnt : counter) {
            oddCnt += cnt % 2;
        }
        return oddCnt < 2;
    }
}

C++

class Solution {
public:
    bool canPermutePalindrome(string s) {
        vector<int> counter(26);
        for (auto& c : s) ++counter[c - 'a'];
        int oddCnt = 0;
        for (int& cnt : counter) oddCnt += cnt % 2;
        return oddCnt < 2;
    }
};

Go

func canPermutePalindrome(s string) bool {
	counter := make([]int, 26)
	for i := range s {
		counter[s[i]-'a']++
	}
	oddCnt := 0
	for _, cnt := range counter {
		oddCnt += cnt % 2
	}
	return oddCnt < 2
}

...