Created
March 23, 2013 22:14
-
-
Save linzhp/5229546 to your computer and use it in GitHub Desktop.
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
public class Solution { | |
public String longestPalindrome(String s) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
String longest = ""; | |
for(int i = 0; i < s.length(); i++) { | |
int j; | |
// pivot at a char | |
for(j = 1; i - j >=0 && i + j < s.length(); j++) { | |
if(s.charAt(i - j) != s.charAt(i + j)) { | |
break; | |
} | |
} | |
String palindrom = s.substring(i-j+1, i+j); | |
if(palindrom.length() > longest.length()) { | |
longest = palindrom; | |
} | |
// pivot between two chars | |
for(j = 0; i - j >= 0 && i + j + 1 < s.length(); j++) { | |
if(s.charAt(i - j) != s.charAt(i + j + 1)) { | |
break; | |
} | |
} | |
palindrom = s.substring(i - j + 1, i + j + 1); | |
if(palindrom.length() > longest.length()) { | |
longest = palindrom; | |
} | |
} | |
return longest; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment