forked from krish-ag/HacktoberFest22-Repo-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_palindromic_substring.java
52 lines (37 loc) · 1.15 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
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
public class longest_palindromic_substring {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String word = sc.next();
String longestPalindromicSubstring = longestPalindrome(word);
System.out.println(longestPalindromicSubstring);
}
public static String longestPalindrome(String s) {
int len = s.length();
if (len < 2)
return s;
int maxLen = 0, pos = 0;
for (int i = 0; i < len; i++) {
int l = i, r = i;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
if (r - l - 1 > maxLen) {
pos = l + 1;
maxLen = r - l - 1;
}
l = i;
r = i + 1;
while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
l--;
r++;
}
if (r - l - 1 > maxLen) {
pos = l + 1;
maxLen = r - l - 1;
}
}
return s.substring(pos, pos + maxLen);
}
}