mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 409. Longest Palindrome.md
This commit is contained in:
parent
6a4947d83d
commit
bed68fca96
26
409. Longest Palindrome.md
Normal file
26
409. Longest Palindrome.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user