描述
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: “babad”
输出: “bab”
注意: “aba” 也是一个有效答案。
示例 2:
输入: “cbbd”
输出: “bb”
Python
将所有的回文数分为奇偶长度的,分别计算最大长度,helper用来得到最大长度的回文
class Solution:
def longestPalindrome(self, s):
res = ""
for i in range(len(s)):
# odd case, like "aba"
tmp = self.helper(s, i, i)
if len(tmp) > len(res):
res = tmp
# even case, like "abba"
tmp = self.helper(s, i, i+1)
if len(tmp) > len(res):
res = tmp
return res
# from left to right
def helper(self, s, l, r):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1; r += 1
return s[l+1:r]
Java
class Solution {
public String longestPalindrome(String s) {
String res = new String();
for(int i=0;i<s.length();i++){
String tmp = this.helper(s,i,i);
if(tmp.length()>res.length()) res = tmp;
tmp = this.helper(s,i,i+1);
if(tmp.length()>res.length()) res = tmp;
}
return res;
}
public String helper(String s,int l,int r){
while(l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)){
l--;
r++;
}
return s.substring(l+1,r);
}
}