class Solution:
"""
@param s: input string
@return: the longest palindromic substring
"""
"""
大致思路:
1.首先呢,给个方法,判断当前字符串是否是回文子串
2.初始化p=0,res =None,假如当前回文子串长度大于p,则更新res
3.外层循环s,内层依次加1循环,1,3,5,7,一直到长度为s为止,最终返回res
"""
def longestPalindrome(self, s):
# write your code here
p,res = 0,None
for i in range(len(s)):
j = i + 1while j <= len(s):
#判断是否是回文字符串,并且和p进行比较,如果小于,则更新
if s[i:j] == s[i:j][::-1] and len(s[i:j]) > p:
p = len(s[i:j])
res = s[i:j]
j += 1return res
双指针写法:
class Solution:
"""
@param s: input string
@return: the longest palindromic substring
"""
'''
大致思路:
1.给出一个方法,判断是否是回文子串,双指针,只要是不等,则break,否则继续判断下去.然后初始化length = 0,如果长度大于length,则更新
'''
def longestPalindrome(self, s):
if not s or s == '':return0
#初始化
l = 0
res = ''for i in range(len(s)):
new_res = self.isPalindrome(s,i,i) if len(self.isPalindrome(s,i,i)) > len(self.isPalindrome(s,i,i+1)) else self.isPalindrome(s,i,i + 1)
if len(new_res) > l:
res = new_res
l = len(new_res)
return res
def isPalindrome(self,s,i,j):
while i >= 0 and j <= len(s) - 1:
if (s[i] != s[j]):
break
i -= 1
j += 1return s[i+1:j]