美文网首页leetcode
266. Palindrome Permutation

266. Palindrome Permutation

作者: 十月里的男艺术家 | 来源:发表于2020-02-25 18:26 被阅读0次

    题目:

    266. Palindrome Permutation

    Given a string, determine if a permutation of the string could form a palindrome.

    Example 1:

    Input: "code"
    Output: false
    

    Example 2:

    Input: "aab"
    Output: true
    

    Example 3:

    Input: "carerac"
    Output: true
    

    Hint:

    Consider the palindromes of odd vs even length. What difference do you notice?
    Count the frequency of each character.
    If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

    266. 回文排列

    描述
    中文
    English
    给定一个字符串,判断字符串是否存在一个排列是回文排列。

    样例1

    输入: s = "code"
    输出: False
    解释:
    没有合法的回文排列
    

    样例2

    输入: s = "aab"
    输出: True
    解释:
    "aab" --> "aba"
    

    样例3

    输入: s = "carerac"
    输出: True
    解释:
    "carerac" --> "carerac"
    

    思路:

    每个字母出现次数数是偶数,可以形成回文串;出现一个奇数次的字母,并且字母总数长度为奇数,也可以形成回文串。

    代码:

    class Solution:
        def canPermutePalindrome(self, s):
            from collections import Counter
            return sum([v % 2 for v in Counter(s).values()]) < 2
    
        def canPermutePalindromeV01(self, s):
            from collections import Counter
            count = Counter(s)
            cnt = 0
            for v in count.values():
                if v % 2 == 1:
                    cnt += 1
            return cnt == 0 or (len(s) % 2 == 1 and cnt == 1)
    
    
    
    func canPermutePalindrome(s string) bool {
        cnt := 0
        counter := make(map[rune]int)
        for _, b := range s {
            counter[b]++
        }
        for _, v := range counter {
            cnt += v % 2
        }
        return cnt < 2
    }
    
    
    

    相关文章

      网友评论

        本文标题:266. Palindrome Permutation

        本文链接:https://www.haomeiwen.com/subject/krhfchtx.html