给定一个包含大写字母和小写字母的字符串,返回通过这些字母构造成的最长的回文串的长度。
统计每个字符出现的次数,有个奇数可以用来当做回文中心,其余的部分只能用偶数计数。
- 时间复杂度 O(n),空间复杂度O(1)
- Runtime: 84 ms, faster than 49.29%
- Memory Usage: 40.8 MB, less than 39.55%
/**
* @param {string} s
* @return {number}
*/
var longestPalindrome = function(s) {
const map = new Map();
for (let item of s) {
if (map.has(item)) {
map.set(item, map.get(item) + 1);
} else {
map.set(item, 1);
}
}
let res = 0;
for (let item of map.values()) {
res += (Math.floor(item / 2) * 2)
if (item % 2 === 1 && res % 2 === 0) {
res++;
}
}
return res;
};
网友评论