我正在尝试使用单词:拼写错误,并通过在相邻字符之间添加“”(空格)将单词拆分为两个单词,并希望得到单词:结果是拼写错误。尝试使用不同的代码,但没有看到任何指导,将有所帮助。
适用于其他建议的代码仅供参考。*请注意,注释掉的代码是我一直在试图获得正确结果的原因。
/**
* Returns possible suggestions for misspelled word
*
* @param tree The Trie that will be checked
* @param word The word in trie that is checked
*/
public static void suggest(TrieNode tree, String word) {
Set<String> result = new HashSet<>();
System.out.println("Suggestions: ");
// Remove a character
for (int i = 0; i < word.length(); ++i)
result.add(word.substring(0, i) + word.substring(i + 1));
// Swap two consecutive characters
for (int i = 0; i < word.length() - 1; ++i)
result.add(word.substring(0, i) + word.substring(i + 1, i + 2) + word.substring(i, i + 1)
+ word.substring(i + 2));
// Replace a character with other
for (int i = 0; i < word.length(); ++i)
for (char c = 'a'; c <= 'z'; ++c)
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i + 1));
// Add a new character
for (int i = 0; i <= word.length(); ++i)
for (char c = 'a'; c <= 'z'; ++c)
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));
// Split word into pair of words by adding a " " between adjacent pairs
// Need help here
for (int i = 0; i < word.length(); ++i)
for (char c = ' '; c <= ' '; ++c)
if (search(tree, word.substring(0, i)) && search(tree, word.substring(i)) == true)
result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));
ArrayList<String> res = new ArrayList<>(result);
int j = 0;
for (int i = 0; i < result.size(); i++)
if (search(tree, res.get(i))) {
if (j == 0)
System.out.print("[");
System.out.print(res.get(i) + ",");
System.out.print("");
j++;
}
System.out.print("]" + "\n");
}
我编写了一个最小的,可运行的代码段,如果在词典中找到了两个单词段,则会拆分单词。
这是我的测试结果
miss spelling
apple
这是代码。重要的方法是splitWord方法。
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
public class DoubleWord implements Runnable {
public static void main(String[] args) {
new DoubleWord().run();
}
@Override
public void run() {
Dictionary dictionary = new Dictionary();
System.out.println(splitWord("missspelling", dictionary));
System.out.println(splitWord("apple", dictionary));
}
public String splitWord(String word, Dictionary dictionary) {
for (int index = 1; index < word.length(); index++) {
String prefix = word.substring(0, index);
if (dictionary.isWordInDictionary(prefix)) {
String suffix = word.substring(index);
if (dictionary.isWordInDictionary(suffix)) {
return prefix + " " + suffix;
}
}
}
return word;
}
public class Dictionary {
private List<String> words;
public Dictionary() {
this.words = setWords();
}
public boolean isWordInDictionary(String word) {
return words.contains(word);
}
private List<String> setWords() {
List<String> words = new ArrayList<>();
words.add("apple");
words.add("miss");
words.add("spelling");
words.add("zebra");
return words;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句