- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
给定一个字符串,我们如何检查它的任何变位词是否可以是回文?
例如让我们考虑字符串“AAC”。它的一个变位词是“ACA”,它是一个回文。如果我们可以从给定字符串的任何变位词形成回文,我们必须编写一个方法,该方法接受一个字符串并输出 true。否则输出假。
这是我目前的解决方案:
from collections import defaultdict
def check(s):
newdict = defaultdict(int)
for e in s:
newdict[e] += 1
times = 0
for e in newdict.values():
if times == 2:
return False
if e == 1:
times += 1
return True
有没有使用 python 库的更短的解决方案?
最佳答案
这是使用标准库的更短的解决方案,使用更正的算法(所有字符数必须是偶数,除了最多一个):
from collections import Counter
def check(s):
return sum(1 for count in Counter(s).itervalues() if count % 2 == 1) <= 1
这很短但很“慢”,因为程序会遍历所有奇数计数,而不是一找到两个就停止。尽快停止的更快的解决方案是:
def check(s):
odd_counts = (count for count in Counter(s).itervalues() if count % 2 == 1)
try:
next(odd_counts) # Fails if there is no odd count
next(odd_counts) # Fails if there is one odd count
except StopIteration:
return True
else:
return False
关于python - 快速和 pythonic 的方法来找出一个字谜是否是回文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22656764/
我的程序运行良好,这只是我需要的一个小建议;首先这是我的代码,用于检查两个单词是否是字谜;效果很好; #include int anagram_check(char [], char []); in
面试问题给定两个输入字符串,您只能交换字符串中的两个连续元素。您必须展示将一个字符串转换为另一个字符串的所有步骤(两个字符串将是彼此的字谜)。例如。口香糖到马克杯 古姆百货公司通用汽车大学微量气体发生
我正在尝试学习 Python。考虑这个简单的 C 语言变位词检查器: bool are_anagrams(const char* str1, const char* str2) { int str
(下面关于我的问题的代码) 根据 this stack overflow question我使用 Pegolon 的方法来生成 NSString 中一组字符的所有可能排列。但是,我现在试图让它不仅生成
testing if strings are anagrams有很多种方式.但是,我想知道是否有一种方法可以只对每个单词进行一次迭代?如果不是,在 Python 中最有效的方法是什么? 我们可以遍历第
我是一名优秀的程序员,十分优秀!