Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python查找字符串的回文_Python - Fatal编程技术网

使用python查找字符串的回文

使用python查找字符串的回文,python,Python,我想从给定的字符串中找到最长的回文 然后打印出来 lines = "forgeeksskeegfor" length = len(lines) a = [lines[i:j+1] for i in range(length) for j in range(i, length)] total = [] for string in a: list(string).reverse() reverse_String = "".join(string) if reverse_S

我想从给定的字符串中找到最长的回文

然后打印出来

lines = "forgeeksskeegfor"
length = len(lines)
a = [lines[i:j+1] for i in range(length) for j in range(i, length)]

total = []
for string in a:
    list(string).reverse()
    reverse_String = "".join(string)

    if reverse_String == string.lower():
      total.append(reverse_String)
print(max(total))
我的当前输出: 斯基弗

预期应为:

geeksskeeg

这是长度10和最长的

而不是查找“字符串”列表中的最大值,您应该查找最大长度。 基于你的方法

lines = "forgeeksskeegfor"
length = len(lines)
a = [lines[i:j+1] for i in range(length) for j in range(i, length)]

total = []
for string in a:
    if string == string[::-1]:
        total.append(string)
max_len = max( [ len(x) for x in total ] )
# result list will contain the longest pallindroms
result_list = [ x for x in total if len(x) == max_len ]
您的回文检查中有一些缺陷

for string in a:
    # the below line will not change anything
    # you are just converting a string to list on the fly 
    # reversing it ,but not storing it somewhere
    list(string).reverse()
    # string is still string of a , and reverse_String and string
    # both will be same.
    reverse_String = "".join(string)

    # not sure why are you converting to lower here
    if reverse_String == string.lower():
      total.append(reverse_String)Hope it helps

希望有帮助。

这可以用动态规划来解决

当字符串中没有回文时,以下代码的最坏运行时间为2^n,因此它将尝试所有可能的解决方案。
但当它找到回文时,它的性能会提高

def find_pal(string, start, end):
    # base case
    if end - start <= 1:
        return (start, end)
    # if a palindrome shows:
    elif string[start] == string[end]:
        # check if its substring is a palindrome also
        next_pal = find_pal(string, start + 1, end - 1)
        if next_pal == (start + 1, end - 1):
            # if it is, then return the longer
            return (start, end)
        else:
            # if it is not, still return any smaller palindrome in string
            return next_pal
    else:
        # if this string is not a palindrome, check for a smaller in a  substring
        next_pal1 = find_pal(string, start + 0, end - 1)
        next_pal2 = find_pal(string, start + 1, end - 0)
        if next_pal1[1] - next_pal1[0] > next_pal2[1] - next_pal2[0]:
            return next_pal1
        else:
            return next_pal2


def find_greatest_pal(string):
    pal_pair = find_pal(string, 0, len(string)-1)
    return string[pal_pair[0]:pal_pair[1]+1]


print(find_greatest_pal("forgeeksskeegfor"))
def find_pal(字符串、开始、结束):
#基本情况
如果结束-开始下一个\u pal2[1]-下一个\u pal2[0]:
下周一返回
其他:
下周一返回
def find_grest_pal(字符串):
pal\u pair=find\u pal(字符串,0,len(字符串)-1)
返回字符串[pal\U pair[0]:pal\U pair[1]+1]
打印(查找最伟大的朋友(“伪造保留”))

这个想法是迭代字符串并生成所有回文,从中间开始,向两边移动。如果我们发现回文长度大于当前长度,我们将用新的回文替换它

def longestPalindrome(s):
    ans = ""
    for i in range(len(s)):
        for k in range(2):
            temp = helper(s, i, i + k)
            if len(temp) > len(ans):
                ans = temp
    return ans

def helper(s, l, r):
    while l >= 0 and r < len(s) and s[r] == s[l]:
        l -= 1
        r += 1
    return s[l+1:r]

回文有两种情况:偶数回文(如正午)和奇数回文(如雷达)。字符串中的每个位置只有两个可能的(最长的)回文。因此,对于每个位置,您只需要通过前后比较字符,找到以该位置为中心的最长偶数和奇数回文

s = "forgeeksskeegfor"

from os import path 
longest = ""
for i in range(1,len(s)-1):
    if min(i,len(s)-i)*2+1 <= len(longest): continue
    for odd in [1,0]:
        if s[i+odd] != s[i-1]: continue
        halfSize = len(path.commonprefix([s[i+odd:],s[:i][::-1]])) 
        if 2*halfSize + odd > len(longest):
            longest = s[i-halfSize:i+halfSize+odd];break
print(longest) # geeksskeeg

有一个简单的方法,此功能可以帮助您:

def longest_palindrome(text):
    text = text.lower()
    longest = ""
    for i in range(len(text)):
        for j in range(0, i):
            chunk = text[j:i + 1]
            if chunk == chunk[::-1]:
                if len(chunk) > len(longest):
                    longest = chunk
    return longest


print(longest_palindrome("forgeeksskeegfor"))

假设子字符串的长度为1个字符(可以在“检查长度”条件中轻松修改),并且可能存在多个长度相同的最长字符串:

def longest_substring(string):
    longest = ""
    for i in range(len(string)):
        for j in range(i + 1, len(string) + 1):
            sub = ''.join(string[i:j])
            if str(sub) == str(sub)[::-1]:
                if len(sub) > len(longest):
                    longest = sub

    return longest

如果您有任何疑问,请检查此项,然后询问,但我打印的结果与我预期的结果不同。事实上,当您执行list(string).reverse()时,它不会改变任何内容。
def longest_palindrome(text):
    text = text.lower()
    longest = ""
    for i in range(len(text)):
        for j in range(0, i):
            chunk = text[j:i + 1]
            if chunk == chunk[::-1]:
                if len(chunk) > len(longest):
                    longest = chunk
    return longest


print(longest_palindrome("forgeeksskeegfor"))
def longest_substring(string):
    longest = ""
    for i in range(len(string)):
        for j in range(i + 1, len(string) + 1):
            sub = ''.join(string[i:j])
            if str(sub) == str(sub)[::-1]:
                if len(sub) > len(longest):
                    longest = sub

    return longest