python - 字符串子串中的最长回文
问题描述
我试图在字符串中找到最长的回文,这是我的看法。
def palindrome(x):
rev = x[::-1]
a = False
if (rev==x):
a = True
return a
def longest_palindrome(s):
last = len(s)
lst = []
for i in range (last):
for j in range (i+1,last):
b = s[i] + s[j]
a = palindrome(b)
if (a==True):
lst.append(b)
else:
continue
return lst
a = input("Enter the string: ")
longest_palindrome(a)
如果我的输入是“aaba”,它会产生输出['aa','aa','aa']
,而输出应该是['aa', 'aba']
. 我迭代的方式有问题吗?
解决方案
我认为您的代码中的问题在于查找子字符串。尝试这个
def palindrome(x):
if len(x) <= 1: ## This condition checks if the length of the string is 1. And if so, it returns False
return False
return x == x[::-1]:
def longest_palindrome(s):
last = len(s)
lst = []
for i in range(last):
for j in range(i, last): ## Iterate from i to last not i+1 to last
b = s[i:j+1] ## Slicing the original string to get the substring and checking if it is a pallindrome or not.
if palindrome(b):
lst.append(b)
else:
continue
return lst
a = input("Enter the string: ")
print(longest_palindrome(a))
. 此代码将有所帮助
推荐阅读
- matlab - 矩阵乘以极坐标形式的数据?
- c# - 如何在 Selenium 驱动程序上替换 js 文件中的源文件或代码?
- c# - OpenTK 使用视口
- php - 如何在 WooCommerce 中从 PHP 读取“商店通知”值
- powerbi - 如何访问 Power BI 中的嵌入代码?
- android - Android蓝牙应用程序在启动时崩溃
- visual-studio-code - VS Code Jupyter 扩展 Markdown 数学不渲染
- python - 无法打印数组的单行我得到了太多的数组错误索引?
- php - 更改字符串,向后排序
- java - Gradle 运行任务不起作用 - 错误:--module-path 需要模块路径规范