lintcode :Longest Palindromic Substring 最长回文子串

时间:2022-03-12 21:05:47

题目

给出一个字符串(假设长度最长为1000),求出它的最长回文子串,你可以假定只有一个满足条件的最长回文串。

样例

给出字符串 "abcdzdcab",它的最长回文子串为 "cdzdc"

挑战

O(n2) 时间复杂度的算法是可以接受的,如果你能用 O(n) 的算法那自然更好。

解题

遍历字符串所有位置,对每个位置左右对等的找回文串,主要要分为两种形式

1.bab形式

2.bb形式

对找到的回文串保留最长的那个就是答案

public class Solution {
/**
* @param s input string
* @return the longest palindromic substring
*/
public String longestPalindrome(String s) {
// Write your code here
if( s == null || s.length() == 1)
return s;
String res = "";
int longest = Integer.MIN_VALUE;
for(int i = 1;i<s.length(); i++){
String str1 = longPalindrome(s,i,i);
String str2 = longPalindrome(s,i-1,i);
str1 = str2.length() >= str1.length()? str2:str1;
if(str1.length()>=longest){
res = str1;
longest = str1.length();
}
}
return res;
}
public String longPalindrome(String s,int start,int end){
int tmp1 = start;
int tmp2 = end;
while( start <= end && end<s.length() && start>=0 && s.charAt(start) == s.charAt(end) ){
start--;
end++;
}
// 没有进行while循环 说明不是回文串,这里只返回第start个字符
if(start ==tmp1 && end == tmp2)
return s.substring(start,start+1);
// start 多减了1
return s.substring(start + 1,end);
}
}

Java Code

总耗时: 19565 ms

class Solution:
# @param {string} s input string
# @return {string} the longest palindromic substring
def longestPalindrome(self, s):
# Write your code here
res = ""
longest = -1
if s == None or len(s) == 1:
return s
for i in range(1,len(s)):
res1 = self.longPalindrome(s,i,i)
res2 = self.longPalindrome(s,i-1,i)
if len(res1)> len(res2) and len(res1)>longest:
res = res1
longest = len(res1)
elif len(res2)> len(res1) and len(res2) >longest:
res = res2
longest = len(res2)
return res
def longPalindrome(self,s,start,end):
tmp1 = start
tmp2 = end
while start>=0 and end<len(s) and s[start] == s[end]:
start-=1
end +=1
if tmp1==start and tmp2 == end:
return s[start]
return s[(start+1):end]

Python Code

总耗时: 865 ms

动态规划

参考链接

定义二维数组table ,当table[i][j] =1 时候表示字符串str中i--j部分是回文串

table[i+1][j-1] == 1 && s.charAt(i) == s.charAt(j)
=>
table[i][j] == 1
初始化:table[i][i] = 1
public class Solution {
/**
* @param s input string
* @return the longest palindromic substring
*/
public String longestPalindrome(String s) {
// Write your code here
if( s == null || s.length() == 1)
return s;
String res = "";
int longest = Integer.MIN_VALUE;
int n = s.length();
int[][] table = new int[n][n];
for(int i=0;i<n;i++){
table[i][i] = 1;
}
for(int l=0;l<n;l++){
for(int i=0;i<n-l;i++){
int j = i+ l;
if( (j-i<=2 || table[i+1][j-1] == 1) && s.charAt(i)==s.charAt(j)){
table[i][j] =1;
if(j-i+1 > longest){
longest = j - i + 1;
res = s.substring(i,j+1);
}
}
}
}
return res;
}
}

j-i<=2 不明白