409. 最长回文串
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入: "abccccdd" 输出: 7 解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
class Solution { public: int longestPalindrome(string s) { unordered_map<char, int> str_cnt; for (auto it : s) { if (str_cnt.find(it) != str_cnt.end()) { str_cnt.emplace(it, 1); } str_cnt[it] ++; } vector<std::pair<char, int>> str_cnt_vec; for (auto it=str_cnt.begin(); it != str_cnt.end(); ++it) { str_cnt_vec.push_back(std::make_pair(it->first, it->second)); } std::sort(str_cnt_vec.begin(), str_cnt_vec.end(), [] (const pair<char, int>& l, const pair<char, int>& r) { return l.first >r.first; }); vector<char> all_huiwen; bool stop = false; int all_cnt = 0; for (auto it: str_cnt_vec) { if (it.second == 1) { stop = true; } all_cnt += it.second /2; if (stop) { break; } } return all_cnt *2 +1; } };
浙公网安备 33010602011771号