LeetCode 409. Longest Palindrome 题解(C++)
题目描述
- Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
- This is case sensitive, for example “Aa” is not considered a palindrome here.
示例
Input:
“abccccdd”Output:
7Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
思路
- 设置一个由52个由bool类型的元素组成的数组,用来记录字符串s中出现的每个字符的次数,比如出现a,则对应数组下标为0里的数值加1,若是A,则在数组的下标为26;这里由ASCII码同英文字母大小写相隔32,且A在ASCII码的前面(比如A的ASCII码十进制表示为65,a的ASCII码十进制表示为97),所以若是大写字母,则需要加上58(大小写相隔的32加上前26个属于小写的位置);
- 遍历字符串s,若该字符相对应的数组元素为false,则将该元素变为true,若是true,则表示该元素已经有访问过,所以palinNum(用来记录回文数的最长长度)加2,并把true改为false;
- 最后,需要对数组的元素进行遍历,若数组有元素为true,则说明存在单数个的字母,所以palinNum需要加1,并直接break退出循环(因这里即使有多个单数的字母,我们也只能取其中的一个放在最长回文的中间位置)。
代码
class Solution
{
public:
int longestPalindrome(string s)
{
int cPos = 0;
for (int i = 0; i < s.size(); ++i)
{
cPos = s[i] - 'a';
if (cPos < 0)
{
cPos += 58;
}
if (cNum[cPos] == false)
{
cNum[cPos] = true;
}
else
{
palinNum += 2;
cNum[cPos] = false;
}
}
for (int i = 0; i < 52; ++i)
{
if (cNum[i] == true)
{
++palinNum;
break;
}
}
return palinNum;
}
};
本篇博客详细介绍了如何使用C++解决LeetCode 409题——找到给定字符串中能构建的最长回文串的长度。通过建立一个布尔数组来记录字符出现的次数,最终找到最长回文串的长度为7,如示例输入'abccccdd'。
1027

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



