leetcode题目:https://leetcode-cn.com/problems/longest-palindrome/
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
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.
示例 1:
输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = "a"
输入:1
示例 3:
输入:s = "bb"
输入: 2
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a"
Output: 1
Example 3:
Input: s = "bb"
Output: 2
第一步:将字符串的每项及对应的数量存入map
第二步:将所有奇数,通过Math.floor(value / 2) * 2,向下取偶数,同时添加到求和里
为了 获得 最长的回文串 ,长度如果小于字符串的长度,可以加一,此操作可以将某个多余的数,添加到最中间
var longestPalindrome = function (s) {
let h = new Map()
let slen = s.length
for (let i = 0; i < slen; i++) {
if (!h.has(s[i])) {
h.set(s[i], 1)
} else {
h.set(s[i], h.get(s[i]) + 1)
}
}
let result = 0
for (let value of h.values()) {
result += Math.floor(value / 2) * 2
}
return result < slen ? result + 1 : result
};
var longestPalindrome = function (s) {
let h = new Map()
let slen = s.length
for (let i = 0; i < slen; i++) {
h.set(s[i], (h.has(s[i]) ? h.get(s[i]) : 0) + 1)//此部分是将上面的代码进行优化
}
let result = 0
for (let value of h.values()) {
result += Math.floor(value / 2) * 2
}
return result < slen ? result + 1 : result
};