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.
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
counter = Counter(s)
return sum(e % 2 for e in counter.values()) < 2
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;
}
}
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;
}
};
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
}