Given a string s
, return true
if a permutation of the string could form a palindrome and false
otherwise.
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:
return sum(v % 2 for v in Counter(s).values()) <= 1
class Solution {
public boolean canPermutePalindrome(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
int n = 0;
for (int v : cnt) {
n += v % 2;
}
return n < 2;
}
}
class Solution {
public:
bool canPermutePalindrome(string s) {
vector<int> cnt(26);
for (char& c : s) ++cnt[c - 'a'];
int n = 0;
for (int& v : cnt) n += v & 1;
return n < 2;
}
};
func canPermutePalindrome(s string) bool {
cnt := make([]int, 26)
for _, c := range s {
cnt[c-'a']++
}
n := 0
for _, v := range cnt {
n += v & 1
}
return n < 2
}
/**
* @param {string} s
* @return {boolean}
*/
var canPermutePalindrome = function (s) {
let ss = new Set();
for (let c of s) {
if (ss.has(c)) {
ss.delete(c);
} else {
ss.add(c);
}
}
return ss.size < 2;
};