
1 贪心算法

class Solution {
public:
int longestPalindrome(string s) {
map<char, int> ch2cnt;
for (auto& ch : s) ch2cnt[ch]++;
int count = 0;
// 是否有奇数
int isOdd = false;
for (auto& m : ch2cnt)
// 1.偶数直接加
if (m.second % 2 == 0) count += m.second;
// 2.奇数自减1,并且标记有过奇数
else if (m.second % 2 == 1) {
count += m.second - 1;
isOdd = true;
}
return isOdd ? count + 1 : count;
}
};


本文介绍了一种使用贪心算法解决字符串中最长回文子串问题的方法。通过统计字符出现次数并判断奇偶性,巧妙地确定了回文子串长度。博主展示了如何在O(n)时间内找到最长回文子串的计数过程。
897

被折叠的 条评论
为什么被折叠?



