A palindrome is a sequence of characters that reads the same backwards and forwards. Given a string, s, find the longest palindromic substring in s..net
Example:
Input: "banana"
Output: "anana"指針
Input: "million"
Output: "illi"code
因爲迴文字符串是對稱的,比較直觀的解法是,依次枚舉每個字符的位置,以當前位置做爲中間點,向左右兩邊擴展,直到遇到不一樣的字符爲止。blog
另外,須要考慮迴文子串長度爲偶數的特殊狀況。這時候,由於中間有2個相同的字符,不太方便操做指針。能夠先對原始字符串作一個預處理:即在每一個位置插入一個 "#" 字符,這樣,就不存在特殊性了。獲得結果後,只須要對子串從新剔除掉人爲插入的 "#" 字符便可。字符串
時間複雜度爲 O(n^2).get
另外,還能夠採用動態規劃法求解,暫未花時間研究。string
思路參考:http://www.javashuo.com/article/p-qzrwdoqk-nm.htmlio
class Solution: def longestPalindrome(self, s): if s == "": return "" # 填充 s2 = "" for c in s: s2 += "#" + c s2 += "#" result = "" # 枚舉每一個位置,向兩邊擴展 for i in range(1, len(s2)): word = s2[i] offset = 1 while offset <= i and i + offset < len(s2): if s2[i - offset] == s2[i + offset]: word = s2[i - offset] + word + s2[i + offset] else: break offset += 1 if len(word) > len(result): result = word # 去除 padding characters result2 = "" for i in range(1, len(result), 2): result2 += result[i] return result2 # Test program s = "tracecars" print(str(Solution().longestPalindrome(s))) # racecar