1、题目描述
2、解题思路
观察回文字符串的特点是:如果字符串的长度为偶数,则所有字符的重复次数都为偶数;如果字符串的长度为奇数,则必有一个字符的重复次数为奇数。
根据这个特点,可以把题目转为:统计字符串 S 每个字符的重复次数,如果有超过 1 个(不包括1个)字符的重复次数为奇数,则返回 false;否则为 true。
3、解题代码
class Solution {
public boolean canPermutePalindrome(String s) {
char[] chars = s.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (char c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int oddCount = 0; // 重复次数为奇数的字符的个数
Set<Character> keySet = map.keySet();
for (Character c : keySet) {
if (map.get(c) % 2 != 0) oddCount++;
}
return oddCount < 2;
}
}