【LeetCode】 409. 最长回文串

版权声明:made by YYT https://blog.csdn.net/qq_37621506/article/details/83717328

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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_37621506/article/details/83717328