我需要编写一个程序,将整个文本文件读入字符串并在其中搜索字谜。输出必须是同一类型的所有字谜词,位于单独的行中,并带有原始的大小写书写。
我尝试了以下方法,但它没有给我想要的结果(显然都是小写):
String input = inputStringBuilder.toString();
input = input.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "").toLowerCase();
String[] sentence = input.split(" ");
Map<String, Set<String>> anagrams = new HashMap<>();
for(int i = 0; i < sentence.length; i++){
char[] charwords = sentence[i].toCharArray();
Arrays.sort(charwords);
String key = new String(charwords);
Set<String> anagramSet = anagrams.get(key);
if (anagramSet == null) {
anagramSet = new HashSet<>();
anagrams.put(key, anagramSet);
}
anagramSet.add(sentence[i]);
}
最佳答案
首先您需要移动toLowerCase()
打电话。
input = input.replaceAll("[^äÄöÖüÜßa-zA-Z ]", ""); // <== Removed from here
String[] sentence = input.split(" ");
Map<String, Set<String>> anagrams = new HashMap<>();
for(int i = 0; i < sentence.length; i++){
char[] charwords = sentence[i].toLowerCase().toCharArray(); // <== Added here
Arrays.sort(charwords);
String key = new String(charwords);
Set<String> anagramSet = anagrams.get(key);
if (anagramSet == null) {
anagramSet = new HashSet<>();
anagrams.put(key, anagramSet);
}
anagramSet.add(sentence[i]);
}
接下来,您需要删除 anagrams
中的条目不包含任何实际字谜的 map 。
问题代码中完全缺少此步骤,其中带有 Set
的映射条目大小为 1 的字符不是实际的字谜。
现在 Set
包含带有原始大小写的单词,非字谜词,例如 "The"
和"the"
可能存在,并且也必须被消除,假设没有真正的字谜。如果存在真正的字谜词,则应保留各种大小写变体。
要检查这一点,请将所有单词添加到小写集合中,并消除该新集合的大小是否为 1,否则保留保留大小写的集合。
// code from above here
for (Iterator<Set<String>> iter = anagrams.values().iterator(); iter.hasNext(); ) {
Set<String> words = iter.next();
if (words.size() == 1) {
iter.remove(); // Not anagram: Single spelling only
} else {
Set<String> lower = new HashSet<>();
for (String word : words)
lower.add(word.toLowerCase());
if (lower.size() == 1) {
iter.remove(); // Not anagram: Multiple case variants, but all same spelling
}
}
}
测试
Input: This is a test of 'the' and 'The'
Result: {}
Input: This is a test of 'the', 'The', and 'eth'
Result: {eht=[the, The, eth]}
<小时/>
如果您不想保留同一单词的所有大小写变体,则只需使集合不区分大小写,使用 new TreeSet<>(String.CASE_INSENSITIVE_ORDER)
.
(代码精简,其中一些使用 Java 8 功能)
Map<String, Set<String>> anagrams = new HashMap<>();
for (String word : input.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "").split(" ")) {
char[] letters = word.toLowerCase().toCharArray();
Arrays.sort(letters);
String key = new String(letters);
anagrams.computeIfAbsent(key, k -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER))
.add(word);
}
anagrams.values().removeIf(words -> words.size() == 1);
测试
Input: This is a test of 'the' and 'The'
Result: {}
Input: This is a test of 'the', 'The', and 'eth'
Result: {eht=[eth, the]}
Input: This is a test of 'The', 'the', and 'eth'
Result: {eht=[eth, The]}
关于java - 有没有办法在搜索字谜时保留单词的大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58535374/