本文主要是介绍409. Longest Palindrome(Leetcode每日一题-2020.03.19),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
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.
Example1
Input:
“abccccdd”
Output:
7
Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.
Solution
偶数个的直接往上加。
奇数个的去掉一个往上加。如果有奇数个的字母,最后再加一。
class Solution {
public:int longestPalindrome(string s) {if(s.empty())return 0;unordered_map<char,int> hash_table;for(auto &c :s){hash_table[c]++;}int ret = 0;int odd = 0;unordered_map<char,int>::const_iterator it = hash_table.begin();for(;it != hash_table.end();++it){if(it->second % 2 == 0){ret += it->second;}else{ret += it->second - 1;odd = 1;}}return ret + odd;}
};
这篇关于409. Longest Palindrome(Leetcode每日一题-2020.03.19)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!