Last active
December 19, 2015 09:49
-
-
Save rfaisal/5936334 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 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(); | |
} | |
} |
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
//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