跳转至

面试题 01.04. 回文排列#

问题描述#

给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。

回文串是指正反两个方向都一样的单词或短语。排列是指字母的重新排列。

回文串不一定是字典当中的单词。

 

示例1:

输入:"tactcoa"
输出:true(排列有"tacocat"、"atcocta",等等)

 

解题思路#

满足回文的条件是,所有字符的个数为偶数,或者其中仅有一个字符的个数为奇数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        count = [False] * 128
        for c in s:
            t = ord(c)
            count[t] = not count[t]

        f = 0
        for v in count:
            if v:
                f += 1
            if f > 1:
                return False
        return True
返回顶部

在手机上阅读