Last active
December 31, 2018 07:30
longestPalindrome
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
class Solution { | |
public String longestPalindrome(String s) { | |
if (s == null || s.length() == 0) { | |
return ""; | |
} | |
String longest = ""; | |
for (int i = 0; i < s.length(); i++) { | |
if (i < s.length() - 1 && s.charAt(i) == s.charAt(i + 1)) { | |
String temp1 = find(s, i, i + 1); | |
if (temp1.length() > longest.length()) { | |
longest = temp1; | |
} | |
} | |
String temp2 = find(s, i, i); | |
if (temp2.length() > longest.length()) { | |
longest = temp2; | |
} | |
} | |
return longest; | |
} | |
private String find(String s, int start, int end) { | |
String longest = s.substring(start, end + 1); | |
while (start - 1 >= 0 && end + 1 < s.length() | |
&& s.charAt(start - 1) == s.charAt(end + 1)) { | |
longest = s.substring(start - 1, end + 2); | |
start = start - 1; | |
end = end + 1; | |
} | |
return longest; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment