LeetCode 409 最长回文串
1.题目描述:
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
2.题解:
方法:哈希表
1.先存储每个字符的数量
2.遍历哈希表中每个元素的数量,先向下取整,再乘以2,求最大回文串长度
3.判断:若最大回文串长度比 院字符串短,可加一
时间复杂度:O(N), 存入每个元素;
空间复杂度:O(N);
C++:
class Solution {
public:
int longestPalindrome(string s) {
unordered_map<char, int> hash ;
int res = 0 ;
for (auto c : s) hash[c]++ ;
for (auto [a,v] : hash ) res += v/2 *2 ;
if (res < s.size()) res++ ;
return res ;
}
};
Golang:
func longestPalindrome(s string) int {
hash :=make(map[rune]int,0)
res := 0
for _, v := range s {
hash[v]++
}
for _, i := range hash {
res += i/2*2
}
if (res < len(s)) {
res++
}
return res
}