Skip to content

Instantly share code, notes, and snippets.

@daifu
Last active December 17, 2015 08:08
Show Gist options
  • Select an option

  • Save daifu/5577720 to your computer and use it in GitHub Desktop.

Select an option

Save daifu/5577720 to your computer and use it in GitHub Desktop.
Longest Palindromic Substring
/*
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
Algorithm:
1. It is a pretty straight forward brute force algorithm, and just move
the center of the parlindrome forward and keep track of the max palindrome
2. There are 2 different situation:
a. the center can be even
b. the center can be odd
3. The big O time complexity will be n^2, and space complexity will be constant.
*/
public class Solution {
public String longestPalindrome(String s) {
// Start typing your Java solution below
// DO NOT write main() function
String evenMax = longestPalindromeHelper(s, 0, 1);
String oddMax = longestPalindromeHelper2(s, 1);
return evenMax.length() > oddMax.length() ? evenMax : oddMax;
}
public String longestPalindromeHelper(String str, int center1, int center2) {
if(str.length() < 2) return str;
int moveLeft;
int moveRight;
String curMax = "";
while(center2 < str.length()) {
moveLeft = center1;
moveRight = center2;
while(moveLeft >= 0 && moveRight < str.length() &&
isPalindrome(str, moveLeft, moveRight)) {
if((moveRight - moveLeft + 1) > curMax.length()) {
curMax = str.substring(moveLeft, moveRight+1);
}
moveLeft--;
moveRight++;
}
center1++;
center2++;
}
return curMax;
}
public String longestPalindromeHelper2(String str, int center) {
if(str.length() < 3) return str;
int moveLeft;
int moveRight;
String curMax = "";
while(center < str.length()) {
moveLeft = center - 1;
moveRight = center + 1;
while(moveLeft >= 0 && moveRight < str.length() &&
isPalindrome(str, moveLeft, moveRight)) {
if ((moveRight - moveLeft + 1) > curMax.length()) {
curMax = str.substring(moveLeft, moveRight+1);
}
moveLeft--;
moveRight++;
}
center++;
}
return curMax;
}
public boolean isPalindrome(String str, int left, int right) {
return str.charAt(left) == str.charAt(right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment