forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindromicSubstring.java
More file actions
56 lines (48 loc) · 1.11 KB
/
LongestPalindromicSubstring.java
File metadata and controls
56 lines (48 loc) · 1.11 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.Scanner;
/**
*
* Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
*
* Example 1:
*
* Input: "babad"
* Output: "bab"
* Note: "aba" is also a valid answer.
*
* Example 2:
*
* Input: "cbbd"
* Output: "bb"
*
*/
public class LongestPalindromicSubstring {
public static void main(String...strings) {
// Input
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
// Print output
System.out.println(longestPalindrome(input));
scanner.close();
}
static String longestPalindrome(String s) {
if (s == null || s.length() < 2) {
return s;
} else {
int start = 0;
int end = 0;
boolean[][] isPalindrome = new boolean[s.length()][s.length()];
for (int j = 1; j < s.length(); j++) {
for (int i = 0; i < j; i++) {
if (s.charAt(i) == s.charAt(j) && (isPalindrome[i + 1][j - 1] || j - i <= 2)) {
isPalindrome[i][j] = true;
if (j - i > end - start) {
start = i;
end = j;
}
}
}
}
return s.substring(start, end + 1);
}
}
}