最长回文串

来源:互联网 发布:淘宝怎么设置好友来访 编辑:程序博客网 时间:2024/06/08 18:15

问题描述:

给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。

数据是大小写敏感的,也就是说,"Aa" 并不会被认为是一个回文串。

样例

给出 s = "abccccdd" 返回 7

一种可以构建出来的最长回文串方案是 "dccaccd"


解题思路:

建立一个map映射a和vector向量b,将s中字母与他重复的个数对应,b记录字母个数,再循环b,算出长度。

代码实现:

class Solution {
public:
    /**
     * @param s a string which consists of lowercase or uppercase letters
     * @return the length of the longest palindromes that can be built
     */
    int longestPalindrome(string& s) {
        // Write your code here
        map<char,int>a;
        vector<int>b;
        for(int i=0;i<s.length();i++){  
            if(a.find(s[i])==a.end()){
                a[s[i]]=1;b.push_back(s[i]);
            }
           else a[s[i]]++;
        }
        int h=0,k=0;
        for(int j=0;j<b.size();j++){ 
            if(a[b[j]]%2==0){
                h=h+a[b[j]];
                a[b[j]]=0;
            }
          else if(a[b[j]]>1){
              h=h+a[b[j]]-1;a[b[j]]=1;
            }
          if(a[b[j]]==1&&k==0){
              h++;k=1;

            }
        }
        return h;
    }
};

解题感悟:

这道题不是自己做出来的,看到别人写的代码才知道也可以这么做。

原创粉丝点击