Q: Given a string s
, return the longest palindromic substring in s
.
Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer.
A: I have two solution.
Solution1 :
I will use dynamic programming to solve this problem.
Two demension array f[i] [j] represents whether the substring s[i...j] is palindromic.
transfer equation:
when i==j, f[i][i] = true;
when i!=j, f[i][j] = (s[i]==s[j]) && f[i+1][j-1] ? true: false;
In order to claculate all the substring, I calculate the substring from length 1 to length n.
Otherwise, it can not calculate the array correctly.
public String longestPalindrome(String s) {
int n = s.length();
String res = s.substring(0,1);
if(s.length()<2){
return s;
}
boolean[][] f = new boolean[n][n];
for(int i=0;i<n;i++){
f[i][i] = true;
}
for(int i=0;i<n-1;i++){
if( s.charAt(i)==s.charAt(i+1)){
f[i][i+1] = true;
if(res.length()<2){
res = s.substring(i,i+2);
}
}
}
for(int l=2;l<n;l++){
for(int i=0;i<n && i+l<n;i++){
int j = i+l;
if(s.charAt(i)==s.charAt(j)){
f[i][j] = f[i+1][j-1];
if(f[i][j] && (j-i+1)>res.length()){
res = s.substring(i,j+1);
}
}
}
}
return res;
}
Solution 2:
I will firstly determine the number of middle element.
There are two possibilities: one or two (a, or aa)
Then I wil loop the whole String and judge whether it is a palindromic.
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
if(n < 2){
return s;
}
String res = s.substring(0,1);
for(int i=0;i<n;i++){
String ans = judge(i,i,s);
if(ans.length()>res.length()){
res = ans;
}
}
for(int i=0;i<n-1;i++){
if(s.charAt(i)!=s.charAt(i+1)) continue;
String ans = judge(i,i+1,s);
if(ans.length()>res.length()){
res = ans;
}
}
return res;
}
public String judge(int begin, int end, String s){
int n = s.length();
while(begin>=0 && end<n && s.charAt(begin)==s.charAt(end)){
begin--;
end++;
}
return s.substring(begin+1, end);
}
}