作者sustainer123 (caster )
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Tue Jun 4 09:42:31 2024
https://leetcode.com/problems/longest-palindrome
409. Longest Palindrome
給定一字串s 回傳用s的字母能建立的最長回文字串的長度
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
Explanation: The longest palindrome that can be built is "a", whose length is
1.
Constraints:
1 <= s.length <= 2000
s consists of lowercase and/or uppercase English letters only.
思路:
哈希表計數
Python Code:
class Solution:
def longestPalindrome(self, s: str) -> int:
record = defaultdict(int)
for n in s:
record[n] += 1
count = 0
one = 1
for v in record.values():
if v % 2 == 1:
if one > 0:
one -= 1
else:
count += 1
return len(s) - count
又是ez的一天 舒服
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.48.144 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1717465353.A.114.html
→ yam276: 什麼! 06/04 09:44
→ sustainer123: 什麼! 06/04 09:44
推 DJYOSHITAKA: 大濕 06/04 09:46
推 SecondRun: 大師 06/04 09:51
推 JIWP: 別卷了 06/04 09:55
推 orangeNoob: 別捲了 06/04 10:50