Leetcode_409_Longest Palindrome
Posted lihello
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode_409_Longest Palindrome相关的知识,希望对你有一定的参考价值。
Longest Palindrome
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.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
这题就是求,用题目中所给字符串中的字符,可以生成的最长回文串的长度。
算法思路:
- 利用字符哈希方法统计字符创中所有字符的数量
- 设最长回文字符串偶数长度为
max_length = 0
- 设置是否有中心点标记
flag = 0
- 遍历每一个字符,字符数为
count
,若count
为偶数max_length += count
,若count
为奇数,max_length += count - 1
,f1ag = 1
- 最终最长回文字串长度为
max_length + flag
class Solution {
public:
int longestPalindrome(std::string s) {
int char_map[128] = {0};
int max_length = 0;
int flag = 0;
for (int i = 0; i < s.length(); i++){
char_map[s[i]]++;
}
for (int i = 0; i < 128; i++){
if (char_map[i] % 2 == 0){
max_length += char_map[i];
}
else{
max_length += char_map[i] - 1;
flag = 1;
}
}
return max_length + flag;
}
};
以上是关于Leetcode_409_Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 409 Longest Palindrome
[leetcode-409-Longest Palindrome]
LeetCode——409. Longest Palindrome
[LeetCode&Python] Problem 409. Longest Palindrome