409. Longest Palindrome

409. Longest Palindrome

1.問題描述

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

已知一個只包括大小寫字符的字符串,求用該字符串中的字符可以生成的最長迴文字符串長度。

This is case sensitive, for example "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

2.C++

int longestPalindrome(string s) {
    map<int, int> my_map;
    map<int, int>::iterator it;

    for(int i=0; i<s.size(); i++) {
        it = my_map.find(s[i]);
        if(it == my_map.end())
           my_map[s[i]] = 1;
        else
            my_map[s[i]]++;
    }

    int flag = 0;
    int num = 0;

    for(it = my_map.begin(); it != my_map.end(); it++) {
        if(it->second % 2 == 0)
            num += it->second;
        else {
            flag = 1;
            num += (it->second - 1);
        }
    }

    return num + flag;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章