# \#409 Longest Palindrome ## *給定一字串s, 回傳s所含的字母能組成的最長回文字串的長度(case sensitive)* ## Log - build 20210805 by syhuang ## xxx - xxx - leetcode submit runtime xx%, memory xx% ```javascript= ``` ## 初見 - 紀錄每個字母出現次數, 跑迴圈把每個字母最接近的偶數相加, 如果有出現奇數則最後結果再+1(回文字串的中間可以放任意一個字母)即為解答 - leetcode submit runtime 70%, memory 90% ```javascript= var longestPalindrome = function(s) { let map = new Map(); for(let i=0; i<s.length; i++){ let t = s[i]; if(map.has(t)) map.set(t,map.get(t)+1); else map.set(t,1); } let HasOddCount = false; let result = 0; map.forEach(function(value){ result += Math.floor(value/2)*2; if(!HasOddCount) HasOddCount = (value%2==1)?true:false; }); return HasOddCount?(result+1):result; }; ``` ## 備註 ## 參考 ###### tags: `leetcode`, `leetcode-easy`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up