找到字符串中最长的回文

回文是指aba 这样从左往右和从右往左读都一样的字符串。

 

思路:

# Input a string baseString

# Define a function check_palindromic_string(), this will return the string and its length if it is a palindromic string

# loop all the sub string of this baseString with check_palindromic_string to get a list of tuple. In the tuple is the palindromic string and its length

# loop the list above to find the longest spalindromic string

 

# Input a string baseString
baseString = raw_input("Please input a string : ")
# Define a function check_palindromic_string(), this will return the string and its length if it is a palindromic string
def check_palindromic_string(s): revers_s = s[::-1] if s == revers_s: return s,len(s)
# loop all the sub string of this baseString with check_palindromic_string to get a list of tuple. In the tuple is the palindromic string and its length
palindromic_list = []
for startIndex in xrange(len(baseString)): endIndex = startIndex+1 while True: if check_palindromic_string( baseString[startIndex:endIndex] ): palindromic_list.append( check_palindromic_string( baseString[startIndex:endIndex] ) ) endIndex += 1 if endIndex > len(baseString): break
# loop the list above to find the longest spalindromic string
for t in palindromic_list:
    if t[1] > 1:
        print t

 

posted on 2015-05-13 13:03  kramer  阅读(200)  评论(0编辑  收藏  举报

导航