7/6 每日一題(每回字串中最長的回文)
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.
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 <= 2000sconsists of lowercase and/or uppercase English letters only.
class Solution:
def longestPalindrome(self, s: str) -> int:
s_freq=Counter(s)
odd_number=0
longest_num=0
odd=0
for i,num in s_freq.items():
longest_num += num
if num %2 != 0:
#找出所有奇數的數量
odd_number +=1
odd += 1 #計算是否存在奇數
if odd:
return longest_num -odd_number+1 #如果有奇數就只保留一個完整的奇數 其他奇數都-1,讓他變成偶數或0
return longest_num
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁