1. 程式人生 > >【LeetCode】 409. 最長迴文串

【LeetCode】 409. 最長迴文串

1.題目

給定一個包含大寫字母和小寫字母的字串,找到通過這些字母構造成的最長的迴文串。
在構造過程中,請注意區分大小寫。比如 “Aa” 不能當做一個迴文字串。
注意:
假設字串的長度不會超過 1010。

2.思路

建立map存放26個大小寫字母的數量;
如果該字母數量為偶數,則sum+=value;
如果該字母數量為奇數,則把value-1;

3.程式碼

class Solution {
public:
    int longestPalindrome(string s) {
        map<char,int>mp;
	int len=
s.length(); for(int i=0;i<len;i++){ mp[s[i]]++; } map<char,int>::iterator t; for(t=mp.begin();t!=mp.end();t++){ cout<<t->first<<" "<<t->second<<endl; } //map<char,int>::iterator t; int sum=0,b=0; for(t=mp.begin();t!=mp.end();t++){ if((t->second)
%2==0) sum+=t->second; else { sum+=((t->second)/2)*2; b++; } } if(b==0) return sum; else return sum+1; } };

4.優秀案例

思路一致,程式碼更加簡潔

class Solution {
public:
    int longestPalindrome(string s) {
        vector<int> mq(52,0);
        for(auto c:s){
            if(c>=
'a'&&c<='z'){ mq[c-'a']++; }else mq[c-'A'+26]++; } int num_q=0; int num=0; for(auto c:mq){ if(c!=0){ if(c%2){ num_q++; } num=num+c; } } if(num_q!=0) num=num-num_q+1; return num; } };