LeetCode 409. Longest Palindrome

来源:互联网 发布:xquartz for mac下载 编辑:程序博客网 时间:2024/04/30 08:01

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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.

如果字母个数是偶数个,直接加进总和。

如果字母个数是奇数个,则判断是否大于最大的奇数max。

如果大于max,则把max-1加进总和,max更新为这个奇数;否则直接把这个奇数加进总和。

class Solution {public:    int longestPalindrome(string s) {        int alpha[100];        int i;        int max = 0;        int count = 0;        for(i = 0; i < 100; i ++) alpha[i] = 0;        for(i = 0; i < s.size(); i ++){            alpha[s[i] - 'A'] ++;        }        for(i = 0; i < 100; i ++){            if(!(alpha[i] % 2)) count += alpha[i];            else{                if(alpha[i] > max){                    if(max) count += max - 1;                    max = alpha[i];                }                 else if(alpha[i]) count += alpha[i] - 1;            }        }        return count + max;    }};


0 0
原创粉丝点击