Python实现Pat 1040. Longest Symmetric String (25)

题目

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given “Is PAT&TAP symmetric?”, the longest symmetric sub-string is “s PAT&TAP s”, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:
Is PAT&TAP symmetric?
Sample Output:
11

解答

line=input()
maxx=0
N=len(line)
for i in range(N):
    j=1
    while i-j+1>=0 and i+j<N:
        if line[i-j+1]!=line[i+j]:
            break
        j += 1
    j-=1
    if j*2>maxx:
        maxx=j*2
    j = 1
    while i - j >=0 and i + j<N:
        if line[i - j] != line[i + j]:
            break
        j += 1
    j -= 1
    if j*2+1>maxx:
        maxx=j*2+1
print (maxx)

这里写图片描述

猜你喜欢

转载自blog.csdn.net/ychanty/article/details/78756220