Day12 - 409. Longest Palindrome

今日题目:409. Longest Palindrome

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

解题技巧

1. str.count(sub, start= 0,end=len(string))

str = 'banana pie banana'
str.count('a',2)
->5

2. collections.Counter()

str2 = 'gallahad'

  • c = Counter(str2)
    ->Counter({'a': 3, 'n': 2, 'b': 1, 's': 1})

  • Counter.items()->['a': 3, 'n': 2, 'b': 1, 's': 1]

  • Counter.values()->[3,2,1,1]

  • Counter.keys()->['a','n','b','s']

My solution

class Solution:
    def longestPalindrome(self, s: str) -> int:
        n = len(s)
        c = collections.Counter(s)
    
        ans = 0
        odd = 0
        
        for v in c.values():
            ans += int(v/2)*2

            if ans%2 ==0 and v%2==1:
                ans +=1
        return ans

Result

https://ithelp.ithome.com.tw/upload/images/20210927/20140843wb7Emx2ypf.png


<<:  Day 12 wireframe 大城市综览 + 天气预报( side project 配对单有意者请进)

>>:  Day12 明明是我(LCOS)先出生的 为什麽大家比较喜欢弟弟妹妹(DLP)

Day12. 一起动手做弹珠台!(2)

今天要来实际运用前两天读的碰撞概念,来为我们的弹珠台加上碰到後的处理与效果。 如果忘了我们的实作目标...

[DAY 30] 复刻 Rails - View 威力加强版 - 2

终於到最後一天了,那就不罗嗦直接进入正题吧! 关於 rendering.rb 之前我们的做法是把 r...

Day.21 Fibonacci

Fibonacci(斐波那契数),大家多少一定会在教课书看过,老实说到我出社会工作都还没搞懂,之前每...

[Day 11] Sass - Operators

Operators 今天要来介绍一下Sass的Oerators-运算功能 虽然在一般的CSS中,我们...

Day 25 - Exception Handling

首先来认识常见的错误类型: EvalError- eval() 执行错误 RangeError - ...