Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created August 8, 2016 23:31
Show Gist options
  • Save jianminchen/ee7e6512cd8fbffb1895e51ebaa4487c to your computer and use it in GitHub Desktop.
Save jianminchen/ee7e6512cd8fbffb1895e51ebaa4487c to your computer and use it in GitHub Desktop.
longest palindrome - facebook code lab - merge two for loops - using array to iterate line 31, 32, line 34, line 35
/**
*
*/
/**
* @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 = "";
for(int i=0; i< len;i++)
{
String s1 = getPalindromeLenC(a, i);
String s2 = getPalindromLenR(a,i);
String[] arr = new String[]{s1, s2};
for(String s : arr)
{
int newOne = s.length();
boolean update = newOne > maxLength;
maxLength = update? newOne : maxLength;
res = update? s : 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