ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

409. 最长回文串

2026/8/13 18:05:29 拓冰建站 浏览量
409. 最长回文串

409. 最长回文串 - 力扣(LeetCode)

给定一个包含大写字母和小写字母的字符串s,返回通过这些字母构造成的最长的 回文串的长度。

在构造过程中,请注意区分大小写。比如"Aa"不能当做一个回文字符串。

示例 1:

输入:s = "abccccdd"输出:7解释:我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

示例 2:

输入:s = "a"输出:1解释:可以构造的最长回文串是"a",它的长度是 1。

题解·

class Solution { public: int longestPalindrome(string s) { map<char,int> dp; for(int i=0;i<s.size();i++){ dp[s[i]] +=1; } int res = 0; int ins = 0; for(const auto& [key,value] : dp){ if(value%2==0){ res +=value; }else{ res +=value-1; ins =1; } } res +=ins; return res; } };