Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
public class Anagrams {
private static final String NON_LETTER_CHAR = "[^a-zA-Z]";
public static String CreateAnagrams(final String sentence) {
final String splitSentence[] = sentence.split(" ");
String anagramSentence = "";
for (int i = 0; i < splitSentence.length; i++) {
final String currentWord = splitSentence[i];
final char[] currentWordChar = currentWord.toCharArray();
final TreeMap nonLetterPosition = new TreeMap<>();
for (int j = 0; j < currentWordChar.length; j++) {
saveNonLetterPos(currentWordChar[j], nonLetterPosition, j);
}
final String onlyLetterWord = currentWord.replaceAll(NON_LETTER_CHAR, "");
String anagramWord = new StringBuffer(onlyLetterWord).reverse().toString();
anagramWord = insertNonLetterSymbol(nonLetterPosition, anagramWord);
anagramSentence = anagramSentence + " " + anagramWord;
}
return anagramSentence;
}
private static String insertNonLetterSymbol(TreeMap nonLetterPosition, String anagramWord) {
for (Map.Entry entry : nonLetterPosition.entrySet()) {
Integer position = entry.getKey();
char nonLetterSymbol = entry.getValue();
anagramWord = new StringBuffer(anagramWord).insert(position, String.valueOf(nonLetterSymbol)).toString();
}
return anagramWord;
}
private static void saveNonLetterPos(char ch, TreeMap nonLetterPosition, int j) {
if (!Character.isLetter(ch)) {
nonLetterPosition. put(j, ch);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question