LeetCode—5. Longest Palindromic Substring
题目
https://leetcode.com/problems/longest-palindromic-substring/description/
寻找最长回文子串。
思路及解法
在字符串中首先选择一个点,从这个点开始向两边扩展开去,不断比较两端的字符是不是相等。需要注意的是,回文子串的长度可奇可偶,所以一开始就应该选择一个点或者两个点开始扩展。
时间复杂度
O
(
n
2
)
O(n^2)
O(n2),空间复杂度??
代码
class Solution {
public String longestPalindrome(String s) {
int len = s.length();
if(len==0 || len==1) return s;
String sub = "";
for(int i=0; i<len; i++){
String tmp = longestSub(i, i, s);
if(tmp.length()>sub.length()) sub=tmp;
tmp = longestSub(i, i+1, s);
if(tmp.length()>sub.length()) sub=tmp;
}
return sub;
}
public String longestSub(int b, int e, String s){
while((b>=0 && e<=s.length()-1) && s.charAt(b)==s.charAt(e)){
b--;
e++;
}
return s.substring(b+1, e);
}
}
class Solution:
def longestPalindrome(self, s: str) -> str:
length = len(s)
if length==0 or length==1:
return s
res = ""
for i in range(length):
temp = self.helper(s, i, i)
if(len(temp)>len(res)):
res = temp;
tmp = self.helper(s, i, i+1)
if(len(tmp)>len(res)):
res = tmp;
return res
def helper(self, s:str, l, r) -> str:
while l>-1 and r<len(s) and s[l]==s[r]:
l -= 1
r += 1
return s[l+1:r]