Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Last active October 7, 2018 21:48
Show Gist options
  • Save hsaputra/e1747eb3f224937f4b0dc2c47095fdc5 to your computer and use it in GitHub Desktop.
Save hsaputra/e1747eb3f224937f4b0dc2c47095fdc5 to your computer and use it in GitHub Desktop.
class Solution {
private int lo, maxLen;
public String longestPalindrome(String s) {
int len = s.length();
if (len < 2)
return s;
for (int i = 0; i < len-1; i++) {
extendPalindrome(s, i, i); //assume odd length, try to extend Palindrome as possible
extendPalindrome(s, i, i+1); //assume even length.
}
return s.substring(lo, lo + maxLen);
}
private void extendPalindrome(String s, int j, int k) {
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
lo = j + 1;
maxLen = k - j - 1;
}
}
}
@hsaputra
Copy link
Author

hsaputra commented Oct 7, 2018

class Solution {
    public String longestPalindrome(String s) {
      // Test cases:
      //  s is null or empty
      //  s has one character
      //  assume s has 1000 chars
      
      if (s == null || s.length() == 0) {
        return "";
      }
      
      // Expand around the center
      int maxLen = 0;
      String longestPal = "";
      for (int i = 0; i < s.length(); i++) {
        int len1 = expand(i, i, s);
        int len2 = expand(i, i + 1, s);
        int curMax = Math.max(len1, len2);
        if (maxLen < curMax) {
          maxLen = curMax;        
          int start = Math.max(0, i - ((maxLen - 1)/2));
          int end = Math.min(s.length() - 1, i + (maxLen/2));
          longestPal = s.substring(start, end + 1);
        }                              
      }
      
      return longestPal;
    }
  
    private int expand(int start, int end, final String s) {
      while (start >= 0 && end < s.length()) {
        char left = s.charAt(start);
        char right = s.charAt(end);
        
        if (left == right) {
          start--;
          end++;
        } else {
          break;
        }
      }
      
      return (end - start - 1);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment