【力扣 075】409. 最長迴文串
阿新 • • 發佈:2022-05-25
409. 最長迴文串
給定一個包含大寫字母和小寫字母的字串 s ,返回 通過這些字母構造成的 最長的迴文串 。
在構造過程中,請注意 區分大小寫 。比如 "Aa" 不能當做一個迴文字串。
示例 1:
輸入:s = "abccccdd"
輸出:7
解釋:
我們可以構造的最長的迴文串是"dccaccd", 它的長度是 7。
示例 2:
輸入:s = "a"
輸入:1
示例 3:
輸入:s = "bb"
輸入: 2
來源:力扣(LeetCode)
連結:https://leetcode.cn/problems/longest-palindrome
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
程式碼實現:
class Solution { public: int longestPalindrome(string s) { int ans = 0; unordered_map<char, int> s_map; for(const auto &c : s) s_map[c]++; for(auto &cur: s_map) ans += cur.second / 2; ans *= 2; if(s.size() > ans) return ans +1; return ans; } };