标签:one cee hat exce rom 字符 note sid sts
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
标签:one cee hat exce rom 字符 note sid sts
原文地址:https://www.cnblogs.com/lihello/p/11748540.html