Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimized LongestPalindromicSubstring.java (Reduced Time Complexity ) #5379

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.thealgorithms.strings;

// Longest Palindromic Substring
import java.util.Scanner;

final class LongestPalindromicSubstring {
Expand All @@ -9,42 +8,39 @@ private LongestPalindromicSubstring() {

public static void main(String[] args) {
Solution s = new Solution();
String str = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter the string: ");
str = sc.nextLine();
System.out.println("Longest substring is : " + s.longestPalindrome(str));
String str = sc.nextLine();
System.out.println("Longest palindromic substring is: " + s.longestPalindrome(str));
sc.close();
}
}

class Solution {
int left = 0, right = -1, maxSize = 0;

public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
for (int i = 0; i < s.length(); i++) {
f(s, i, i); // Odd length palindromes
f(s, i, i + 1); // Even length palindromes
}
int n = s.length();
String maxStr = "";
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
if (isValid(s, i, j)) {
if (j - i + 1 > maxStr.length()) { // update maxStr
maxStr = s.substring(i, j + 1);
}
}
}
}
return maxStr;
return s.substring(left, right + 1);
}

private boolean isValid(String s, int lo, int hi) {
int n = hi - lo + 1;
for (int i = 0; i < n / 2; ++i) {
if (s.charAt(lo + i) != s.charAt(hi - i)) {
return false;
public void f(String s, int l, int r) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public void f(String s, int l, int r) {
private void expandAroundCenter(String s, int l, int r) {

while (l >= 0 && r < s.length()) {
if (s.charAt(l) == s.charAt(r)) {
l--;
r++;
} else {
break;
}
}
return true;
int size = r - l - 1;
if (maxSize < size) {
left = l + 1;
right = r - 1;
maxSize = size;
}
}
}
Loading