【发布时间】:2017-04-22 17:18:19
【问题描述】:
所以我在这个网站和其他网站上查看了有关如何在 Python 上遍历字符串、找到特定子字符串、反转它并检查两者是否相等以获得回文的信息。这就是问题所在,因为某些测试用例很难获取,并且让我对如何通过索引找到它们感到困惑。
这是我的代码,适用于所有人,但有两个测试用例:
def countPalindromes(s):
count = 0
firstindex = 0
lastindex = len(str)-1
while firstindex != lastindex and firstindex <= lastindex:
ch1 = s[firstindex:lastindex]
ch2 = s[lastindex:firstindex:-1]
if ch1 == ch2:
count +=1
firstindex +=1
lastindex -=1
return count
此代码适用于以下回文:“racecar”、“”和“abqc”。 它不适用于这些回文“aaaa”和“abacccaba”。
对于“aaaa”,有 6 个回文,对于“abacccaba”,有 8 个回文。这就是我的问题发生的地方,我根本无法弄清楚。对于“aaaa”的 6 个回文,我得到 aaaa,aaa,aa,每个回文两次。对于“abacccaba”,我不知道 abacccaba、bacccab、acca、ccc、aba、aba 的 8 个回文。
我知道这是一个令人困惑的问题,但我不知道如何解决这个问题,因为我只得到 2 的“aaaa”和 4 的“abacccaba”。有什么想法可以删除子字符串并获取这些值吗?
提前致谢!
【问题讨论】:
标签: python-2.7