python - 回文无法通过所有测试用例

标签 python python-3.x string pointers data-structures

给定一个字符串 s , 确定它是否是回文,只考虑字母数字字符并忽略大小写。
为什么以下解决方案不接受某些测试用例?

s = "".join(s)
s = s.lower()
if s==s[::-1]:
    return "true"
else:
    return "false"
输入:s = "A man, a plan, a canal: Panama"输出:true接受此测试用例:
输入:s = "race a car"输出:false此测试用例返回 true 而不是 false

最佳答案

目前是returning false对于这两种情况。
根据问题中的这一部分

considering only alphanumeric characters and ignoring cases.


您可以首先使用 re.sub 和模式 [^a-zA-Z0-9]+ 从字符串中删除所有非字母数字字符匹配除列出的字母数字范围之外的所有字符。
import re
strings = [
    "race a car",
    "A man, a plan, a canal: Panama"
]

for s in strings:
    s = re.sub(r"[^a-zA-Z0-9]+", "", "".join(s).lower())
    if s == s[::-1]:
        print("true: for {0}".format(s))
    else:
        print("false: for {0}".format(s))
输出
false: for raceacar
true: for amanaplanacanalpanama
Python demo

关于python - 回文无法通过所有测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67181687/

相关文章:

javascript - QML Javascript "console.log"与 UTF-8

c# - 通用类和约束

python - 无法安装库以在Anaconda中打开音频文件

python - sklearn将模型保存到磁盘,但只获取数组

python-3.x - 陷入python中的循环 - 只返回第一个值

python - 访问 `.days` 以获得 pandas 时间增量系列

python - 创建 super 用户django时出错

python - 如何从 Python 中调用 'git pull'?

python - 从文本中剥离专有名词

string - Grails-将字符串转换为日期,然后再转换回字符串