Create 409. Longest Palindrome.md

This commit is contained in:
唐树森 2018-09-15 23:22:31 +08:00 committed by GitHub
parent 6a4947d83d
commit bed68fca96
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,26 @@
# [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/description/)
# 思路
给出一些包含大小写的字母,判断能由这些字母组成的回文串最长为多少。
分析如果某个字母出现次数为偶数那肯定全部都能放进目标最长的回文串如果某个字母出现次数为奇数则只能放下不超过这个奇数的最大偶数也就是减1个该字母。
不过需要注意的是如果出现了出现次数为奇数的字母则最后的回文串长度按照上诉思路计算后还应该加1此时回文串长度为奇数例如dccaccd。
时间复杂度O(n) 空间复杂度O(1)
# 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;
}
};
```