LeetCode贪心 最长回文串
生活随笔
收集整理的這篇文章主要介紹了
LeetCode贪心 最长回文串
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, “Aa” is not considered a palindrome here.
思路
首先學(xué)習(xí)一個新單詞,palindrome回文。
主要思路是哈希表+貪心,隨后對哈希表進(jìn)行遍歷。當(dāng)元素值是奇數(shù)時,需要用一個flag記錄一下出現(xiàn)過奇數(shù)的,sum累加上奇數(shù)值-1(因為當(dāng)有多個奇數(shù)出現(xiàn)時,不可能直接拼接成一個回文串);當(dāng)元素是偶數(shù)時,sum直接累加上偶數(shù)值。在循環(huán)結(jié)束后,若flag為true,表明組成的回文串中有出現(xiàn)奇數(shù)次數(shù)的字母,因此sum需要再加上1。
代碼
class Solution { public:int longestPalindrome(string s) {unordered_map<char, int> letter_map;for(auto c : s){letter_map[c]++;}int sum = 0, temp;bool flag = false;for(auto it : letter_map){temp = it.second;if(temp % 2 == 1){sum += temp - 1;flag = true;}else {sum += temp;}}if(flag == true)sum += 1;return sum;} };總結(jié)
以上是生活随笔為你收集整理的LeetCode贪心 最长回文串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 消息称三星 Exynos 2400 芯片
- 下一篇: numpy创建zeros数组时报错Typ