T
T
Tima2020-07-07 22:48:42
Java
Tima, 2020-07-07 22:48:42

How to perform string anagram only for literals in Java language?

How to perform string anagram only for literals in Java language?
Those. non-literal characters must remain in their position.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tima, 2020-07-08
@BlachHugh

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 question

Ask a Question

731 491 924 answers to any question