-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathLongestPalindromicSubstring.java
43 lines (37 loc) · 1.44 KB
/
LongestPalindromicSubstring.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
42
43
package com.geeksforgeeks.string;
public class LongestPalindromicSubstring {
public static void main(String[] args) {
System.out.println(getLongestPalindromicSubstring("forgeeksskeegfor"));
}
public static String getLongestPalindromicSubstring(String str) {
char[] charArr = str.toCharArray();
StringBuilder builder = new StringBuilder();
int lowIndex = 0, highIndex = 1;
int maxLength = 0, start = 0;
for (int i = 1; i < charArr.length; i++) {
lowIndex = i - 1;
highIndex = i;
// For Even String
while (lowIndex >= 0 && highIndex < charArr.length && (charArr[lowIndex] == charArr[highIndex])) {
if (highIndex - lowIndex + 1 > maxLength) {
start = lowIndex;
maxLength = highIndex - lowIndex + 1;
}
--lowIndex;
++highIndex;
}
lowIndex = i - 1;
highIndex = i + 1;
// For Odd String
while (lowIndex >= 0 && highIndex < charArr.length && (charArr[lowIndex] == charArr[highIndex])) {
if (highIndex - lowIndex + 1 > maxLength) {
start = lowIndex;
maxLength = highIndex - lowIndex + 1;
}
--lowIndex;
++highIndex;
}
}
return str.substring(start, start + maxLength);
}
}