MDGSF Software Engineer

[算法学习][leetcode] 409 Longest Palindrome

2017-08-31
mdgsf
Art

https://leetcode.com/problems/longest-palindrome/description/

题目

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.

题目翻译

题目解析

参考答案

#include <iostream>
using namespace std;

class Solution {
public:
    int longestPalindrome(string s) {

        int hashtable[128] = { 0 };
        for (char c : s)
        {
            hashtable[c]++;
        }

        bool bHasOdd = false;
        int iResult = 0;
        for (int i = 0; i < 128; i++)
        {
            if (hashtable[i] % 2 == 0)
            {
                iResult += hashtable[i];
            }
            else
            {
                iResult += hashtable[i] - 1;
                bHasOdd = true;
            }
        }

        return bHasOdd ? iResult + 1 : iResult;
    }
};

int main()
{
    Solution o;
    int iRet = o.longestPalindrome("abccccdd");
    cout << iRet << endl;
    return 0;
}

weixingongzhonghao

Similar Posts

Comments