Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 14, 2017 17:23
Show Gist options
  • Select an option

  • Save cixuuz/ada649f394417804fb8020452d29976b to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/ada649f394417804fb8020452d29976b to your computer and use it in GitHub Desktop.
[5. Longest Palindromic Substring] #leetcode
public class Solution {
public static String longestPalindrome(String s) {
if (s == null) return null;
if (s.length() <= 1) return s;
int start = 0;
int end = 0;
// foreach find longest
for (int i = 0; i < s.length(); i++) {
int p1 = findPalindrome(s, i, i);
int p2 = findPalindrome(s, i, i + 1);
int maxLen = Math.max(p1, p2);
if (maxLen > end - start) {
start = i - (maxLen - 1) / 2;
end = i + maxLen / 2 + 1;
}
}
// output
return s.substring(start, end);
}
private static int findPalindrome(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
// check left and right
left--;
right++;
}
return right - left - 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment