LeetCode/solutions/409. Longest Palindrome.md
2019-09-13 23:08:41 +08:00

27 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/)
# 思路
给出一些包含大小写的字母,判断能由这些字母组成的回文串最长为多少。
分析如果某个字母出现次数为偶数那肯定全部都能放进目标最长的回文串如果某个字母出现次数为奇数则只能放下不超过这个奇数的最大偶数也就是减1个该字母。
不过需要注意的是如果出现了出现次数为奇数的字母则最后的回文串长度按照上诉思路计算后还应该加1此时回文串长度为奇数例如dccaccd。
时间复杂度O(n) 空间复杂度O(1)
# C++
```C++
class Solution {
public:
int longestPalindrome(string s) {
vector<int>count(52, 0);
for(int i = 0; i < s.size(); i++){
if(s[i] >= 'a' && s[i] <= 'z') count[s[i] - 'a']++;
else count[s[i] - 'A' + 26]++;
}
int odd_tag = 0, res = 0;
for(int n: count){
if(n % 2 == 1) odd_tag = 1;
res += (n - n % 2);
}
res += odd_tag;
return res;
}
};
```