Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active December 19, 2015 09:49
Show Gist options
  • Save rfaisal/5936334 to your computer and use it in GitHub Desktop.
Save rfaisal/5936334 to your computer and use it in GitHub Desktop.
public class PalindromeMaker {
public String make(String baseString) throws Exception{
int[] hash= new int[26];
for(int i=0;i<baseString.length();i++){
char ch=baseString.charAt(i);
if(ch<'A' || ch>'Z') throw new Exception("Wrong Input");
hash[ch-'A']++;
}
boolean check=false;
StringBuilder begin=new StringBuilder();
StringBuilder end=new StringBuilder();
for(int i=0;i<26;i++){
if(hash[i]%2==1){
if(check) return "";
else check=true;
}
while(hash[i]>1){
begin.append((char)(i+'A'));
end.append((char)(i+'A'));
hash[i]-=2;
}
}
for(int i=0;i<26;i++){
if(hash[i]==1){
begin.append((char)(i+'A'));
break;
}
}
begin.append(end.reverse());
return begin.toString();
}
}
//passed Topcoder System Tests
public class PalindromeMakerTest {
@Test
public void testMake() throws Exception {
assertEquals("ABBA", new PalindromeMaker().make("AABB"));
assertEquals("ABABA", new PalindromeMaker().make("AAABB"));
assertEquals("AABCBAA", new PalindromeMaker().make("ABACABA"));
assertEquals("", new PalindromeMaker().make("ABCD"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment