我正在寻找改进CodeFight上提交的代码的建议。实际上它运作良好,但我知道它可以改进。
该函数的目标是找出是否可以重新排列字符串以形成回文。我把这个问题作为一个简单的问题:任何字母必须除以2除非字符串是奇数。在这种情况下,除1之外的所有字母都必须除以2。
def palindromeRearranging(inputString):
i = 0
count = 0
# a count to know how many char cant be
# divided by 2. used only for odd strings
if len(inputString) % 2 == 0:
# if len is pair
# every char counts has to be divided by 2
for letter in inputString:
if inputString.count(letter) % 2 != 0:
return False
elif len(inputString) == 1:
# if there is only one char
# string is palindrome
return True
elif len(inputString) % 2 != 0:
# if len is odd
# every char counts has to be divided by 2
# except for 1 char
for letter in inputString:
if inputString.count(letter) % 2 != 0:
count += 1
if count > 1:
return False
return True
有没有更好的方法来编写我的解决方案?谢谢导师!
答案 0 :(得分:1)
尝试这种方法
from collections import Counter
def palindromeRearranging(s):
return sum(i % 2 == 1 for i in Counter(s).values()) <= 1