最长回文串

来源:互联网 发布:夏河淘宝日货是正品吗 编辑:程序博客网 时间:2024/06/03 21:53

题目:

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

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

思路:

用哈希表(词典)结构。

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        if (s.length() == 0) return 0;        map<char, int> Amap;        map<char, int>::iterator It1;        for (int i = 0; i < s.length(); i++) {            if (Amap[s[i]] == 0) {                Amap[s[i]] = 1;            } else {                Amap[s[i]] += 1;            }        }        int sum1 = 0;        int flag_1 = 0;        for (It1 = Amap.begin(); It1 != Amap.end(); It1++) {            if ((It1->second) > 1) {                sum1 += int((It1->second)/2) * 2;            }            if ((It1->second) %2 == 1) {                flag_1 = 1;            }        }        if (flag_1 == 1) {            sum1 += 1;        }        return sum1;    }};


原创粉丝点击