-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongest_Palindromic_Substring.java
41 lines (37 loc) · 1.06 KB
/
Longest_Palindromic_Substring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public String longestPalindrome(String s) {
boolean [][] dp = new boolean [s.length()][s.length()];
String ans="";
String temp= "";
for(int gap=0;gap<s.length();gap++){
for(int i=0,j=gap; j<dp.length;i++,j++){
if(gap==0){
dp[i][j]=true;
}
else if(gap==1){
if(s.charAt(i)==s.charAt(j)){
dp[i][j]=true;
}
else{
dp[i][j]=false;
}
}
else{
if(s.charAt(i)==s.charAt(j) && dp[i+1][j-1]==true){
dp[i][j]=true;
}
else{
dp[i][j]=false;
}
}
if(dp[i][j]) {
temp = s.substring(i, j+1);
if(ans.length() < temp.length()) {
ans = temp;
}
}
}
}
return ans;
}
}