Skip to content

Commit 0e32ff6

Browse files
authored
Create Longest_Palindromic_Substring.java
1 parent 06cb787 commit 0e32ff6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//LeetCode 5. Longest Palindromic Susbtring
2+
//Question - https://leetcode.com/problems/longest-palindromic-substring/
3+
4+
class Solution {
5+
public String longestPalindrome(String s) {
6+
int n = s.length();
7+
if(n == 0) return s;
8+
9+
//isPalin[i][j] indicates if the substring s(i...j) is a palindrome or not
10+
boolean isPalin[][] = new boolean[n][n];
11+
/*
12+
A string is a palindrome if -
13+
1. Length of string is 0 or 1
14+
2. If length of string is 2 then s[i] == s[j]
15+
3. If length of string is greater than or equal to 3, check
16+
3.1. if s[i] == s[j]
17+
3.2. if dp[i+1][j-1] is true, ie. s[i+1...j-1] is a palindrome or not
18+
19+
For the 3rd condition it can be seen that for a problem s[i...j] the subproblem is s[i+1...j-1]
20+
To solve the problem, subproblem must be pre-computed.
21+
So, the outer loop starts in a reverse way, ie. from n...0 (i+1 for each i)
22+
The inner loop starts from i and moves up to n, ie. i...n
23+
24+
Using a nested loop we are considering all substrings.
25+
*/
26+
String res = null;
27+
28+
for(int i = n - 1 ; i >= 0 ; i--){
29+
for(int j = i ; j < n ; j++){
30+
//condition (2) and (3)
31+
isPalin[i][j] = (s.charAt(i) == s.charAt(j)) && ((j - i + 1 < 3) || isPalin[i+1][j-1]);
32+
33+
//storing the longest palindromic substring
34+
if(isPalin[i][j] && (res == null || j - i + 1 > res.length())){
35+
res = s.substring(i, j+1);
36+
}
37+
}
38+
}
39+
40+
return res;
41+
}
42+
}

0 commit comments

Comments
 (0)