#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Longest Palindromic Substring
中文:最长回文子串
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
if not length:
return 0
max_len = 1
max_start = 0
max_end = 0
for i in range(length):
#回文串为奇数
left,right = i - 1,i + 1
while left >=0 and right < length and s[left] == s[right]:
if right - left + 1 > max_len:
max_len,max_start,max_end = right - left + 1,left,right
left -= 1
right += 1
#回文串为偶数
left,right = i,i + 1
while left >=0 and right < length and s[left] == s[right]:
if right - left + 1 > max_len:
max_len,max_start,max_end = right - left + 1,left,right
left -= 1
right += 1
return s[max_start : max_end + 1]
if __name__ == "__main__":
s = Solution()
print s.longestPalindrome('aaaa')
7 - leetcode Longest Palindromic Substring
最新推荐文章于 2025-08-10 20:50:18 发布