Last active
October 7, 2018 21:48
-
-
Save hsaputra/e1747eb3f224937f4b0dc2c47095fdc5 to your computer and use it in GitHub Desktop.
Longest Palindromic Substring - https://leetcode.com/problems/longest-palindromic-substring/description/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Author
hsaputra
commented
Oct 7, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment