最长回文串

来源:互联网 发布:502 bad gateway nginx 编辑:程序博客网 时间:2024/06/11 09:15

题目:

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

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

 注意事项

假设字符串的长度不会超过 1010

样例

给出 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;}//这里少判断等于1时
          if(a[b[j]]==1&&k==0) {h++;k=1;}
        }
        return h;
    }
};

感想:

通过这道题我知道了原来map映射还能这样写,直接像数组那样,不用插入,难度倒没什么。

原创粉丝点击