class Solution {
public int longestPalindrome(String s) {
//首先创建一个hash表来统计字符频率
Map<Character, Integer> map = new HashMap<>();
char[] chars = s.toCharArray();
for(char c : chars) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
//然后我们遍历map的值, 取所有奇数和偶数次字符的向下取整偶数个字符,
//只要出现过奇数次的字符,最后我们都可以取一个放到最中间
int length = 0;
//设置一个奇数次标志位
boolean hasOdd = false;
for(int l : map.values()) {
length += (l / 2) * 2;
if(l % 2 == 1) {
hasOdd = true;
}
}
return (hasOdd == true) ? length + 1: length;
}
}
Leetcode 最长回文串
最新推荐文章于 2025-06-09 23:05:05 发布