Skip to content

Commit d2d697b

Browse files
Optimized LongestPalindromicSubstring.java
Optimized Longest Polindromic Substring from avg run time of 532ms to 13ms
1 parent ce4eb55 commit d2d697b

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed
Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.thealgorithms.strings;
22

3-
// Longest Palindromic Substring
43
import java.util.Scanner;
54

65
final class LongestPalindromicSubstring {
@@ -9,42 +8,39 @@ private LongestPalindromicSubstring() {
98

109
public static void main(String[] args) {
1110
Solution s = new Solution();
12-
String str = "";
1311
Scanner sc = new Scanner(System.in);
1412
System.out.print("Enter the string: ");
15-
str = sc.nextLine();
16-
System.out.println("Longest substring is : " + s.longestPalindrome(str));
13+
String str = sc.nextLine();
14+
System.out.println("Longest palindromic substring is: " + s.longestPalindrome(str));
1715
sc.close();
1816
}
1917
}
2018

2119
class Solution {
20+
int left = 0, right = -1, maxSize = 0;
2221

2322
public String longestPalindrome(String s) {
24-
if (s == null || s.length() == 0) {
25-
return "";
23+
for (int i = 0; i < s.length(); i++) {
24+
f(s, i, i); // Odd length palindromes
25+
f(s, i, i + 1); // Even length palindromes
2626
}
27-
int n = s.length();
28-
String maxStr = "";
29-
for (int i = 0; i < n; ++i) {
30-
for (int j = i; j < n; ++j) {
31-
if (isValid(s, i, j)) {
32-
if (j - i + 1 > maxStr.length()) { // update maxStr
33-
maxStr = s.substring(i, j + 1);
34-
}
35-
}
36-
}
37-
}
38-
return maxStr;
27+
return s.substring(left, right + 1);
3928
}
4029

41-
private boolean isValid(String s, int lo, int hi) {
42-
int n = hi - lo + 1;
43-
for (int i = 0; i < n / 2; ++i) {
44-
if (s.charAt(lo + i) != s.charAt(hi - i)) {
45-
return false;
30+
public void f(String s, int l, int r) {
31+
while (l >= 0 && r < s.length()) {
32+
if (s.charAt(l) == s.charAt(r)) {
33+
l--;
34+
r++;
35+
} else {
36+
break;
4637
}
4738
}
48-
return true;
39+
int size = r - l - 1;
40+
if (maxSize < size) {
41+
left = l + 1;
42+
right = r - 1;
43+
maxSize = size;
44+
}
4945
}
5046
}

0 commit comments

Comments
 (0)