Created
September 14, 2017 17:23
-
-
Save cixuuz/ada649f394417804fb8020452d29976b to your computer and use it in GitHub Desktop.
[5. Longest Palindromic Substring] #leetcode
This file contains hidden or 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
| 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