Longest Palindrome问题及解法

来源:互联网 发布:淘宝网人民法院拍卖 编辑:程序博客网 时间:2024/06/08 07:34
问题描述:

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 de >"Aa"de> is not considered a palindrome here.

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

示例:

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

问题分析:

本题主要是从给定的字母里选出一部分组成最长的回文串。转换一下,就是相当于把里面出现偶数次的字母出现次数加起来,然后再把里面出现奇数次的字母出现次数减一后再相加,等到sum。若是给定的字母中字母出现次数有奇数次,那么sum = sum + 1.最终返回sum即可。

过程详见代码:

class Solution {public:    int longestPalindrome(string s) {        vector<int> mapping(256,0);        for(int i = 0;i < s.length(); i++)        {        mapping[s[i]]++;}int flag = 0;int sum = 0;for(int i = 0;i < 256;i++){int temp = mapping[i];if(temp % 2) {sum += temp - 1;flag = 1;}else sum += temp;}return (flag== 1) ? sum + 1 : sum;    }};

0 0
原创粉丝点击