Created
August 8, 2016 22:59
-
-
Save jianminchen/08126ba3d168498695e619f7fded444a to your computer and use it in GitHub Desktop.
facebook code lab - longest palindrome - first writing
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
/** | |
* | |
*/ | |
/** | |
* @author jchen | |
* | |
*/ | |
package test; | |
public class testing{ | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
String test = longestPalindrome("abb"); | |
System.out.print(test); | |
} | |
public static String longestPalindrome(String a) { | |
if(a==null) | |
return ""; | |
int len = a.length(); | |
int maxLength = 0; | |
String res = ""; | |
// center aba style | |
for(int i=0; i< len;i++) | |
{ | |
String s1 = getPalindromeLenC(a, i); | |
int newOne = s1.length(); | |
boolean update = newOne > maxLength; | |
maxLength = update? newOne : maxLength; | |
res = update? s1 : res; | |
} | |
// abba style | |
for(int i=0; i< len; i++) | |
{ | |
String s1 = getPalindromLenR(a,i); | |
int newOne = s1.length(); | |
boolean update = newOne > maxLength; | |
maxLength = update? newOne : maxLength; | |
res = update? s1 : res; | |
} | |
return res; | |
} | |
/* abcba style, center position is char c */ | |
public static String getPalindromeLenC(String s, int index) | |
{ | |
int len = s.length(); | |
int span = 1; | |
while((index + span) < len && (index-span) >=0) | |
{ | |
if(s.charAt(index+span) == s.charAt(index-span)) | |
span++; | |
else | |
break; | |
} | |
return s.substring(index-span +1, index+span -1); | |
} | |
/*abba style, center position is first b */ | |
public static String getPalindromLenR(String s, int index) | |
{ | |
int len = s.length(); | |
int begin =index; | |
int end = index +1; | |
boolean hasOne = false; | |
while(begin >= 0 && end < len) // len, not len-1 | |
{ | |
if(s.charAt(begin) == s.charAt(end)) | |
{ | |
hasOne = true; | |
begin --; | |
end ++; | |
} | |
else | |
break; | |
} | |
return (hasOne)? s.substring(begin+1, end):""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Practice notes:
4 . line 33 - 36 bug removal - use extra boolean update, since line 35 - update maxLength, so line 36 update boolean should not be used. Saved status