亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字符串子串中最長的回文

字符串子串中最長的回文

智慧大石 2021-11-23 20:02:34
我試圖找到字符串中最長的回文,這是我的看法。def palindrome(x):    rev = x[::-1]    a = False    if (rev==x):        a = True    return adef 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 lsta = input("Enter the string: ")longest_palindrome(a)如果我的輸入是“aaba”,它會產生輸出,['aa','aa','aa']而輸出應該是['aa', 'aba']. 我迭代的方式有問題嗎?
查看完整描述

2 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

我認為您的代碼中的問題在于查找子字符串。嘗試這個


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))

. 此代碼將有所幫助


查看完整回答
反對 回復 2021-11-23
?
一只甜甜圈

TA貢獻1836條經驗 獲得超5個贊

這應該可以正常工作。


def longest_palindrome(s):


    last = len(s)

    lst = []

    for i in range(last):

        for j in range(i+1, last):

            b = s[i:j+1]       #Here's the catch.

            a = palindrome(b)

            if a:

                lst.append(b)

    return lst

您可以使用打印語句進行檢查。如果在代碼中添加 print 語句,您會看到最多只檢查長度為 2 的字符串(“aa”、“ab”、“ba”)。


我希望它有幫助。


查看完整回答
反對 回復 2021-11-23
  • 2 回答
  • 0 關注
  • 258 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號