我有一个程序会提示用户输入 9 个字符。一旦这些字符出现在程序中,程序应该通过将它们与字典文件进行比较来使用这些字母创建可能的最长单词。
该程序当前存储 9 个字母并在字典文件中读取,但我不知道从哪里开始创建单词。
我需要帮助的只是单词创建者。如果有人知道如何从数组中的字符创建单词,你能帮帮我吗
您应该采用另一种方式:遍历您的字典文件并检查每个单词是否完全由指定的字母组成。
假设用户 Allrdy 输入了 9 个字符,字典存储在一个数组中:
我猜你正在使用一个char数组?我猜字典通常是排序的,所以数组要么在我的条件下。
您应该使用 for 循环扫描数组
// these are the scanned chars
char[] char = new chars[];
// has to be loaded from somewhere.
String[] dic = new String[100];
String found = "";
//.....reading chars
String longest = "";
for(int i = 0 : i<9;++i) {
// look if an element exists, matching the letter a at the beginning
if(exists) {
// you found a word? nice safe it in a variable called found otherise compare longest and found, to check which once length is greater
found = foundWordBefore;
for(int j = (i+1)%10;j!=i+9%10;++j) {
// look if there is another word matching the first letter and the second one
if(exists) {
for(int k = (i+2)%10;k!=i+9%10;++k) {
//same again as before, continue until you reached last (i+8)%9
}
}
}
}
else {
// if you found the nothing, compare the longest you found yet, to the longest you found before
if(longest.length < found.length) {
longest = found;
}
}
}
希望这个伪帮助和工作:D
因为您似乎没有得到解决方案,这是我的,它应该可以工作
import java.util.ArrayList;
public class Test{
public String[] dict = new String[] {"hi","das","bad","fenster","esel","bahi","tfshi"};
public char[] input = new char[]{'a','b','d','h','i','s','f','t'};
public String longestString = dict[0];
public Test() {
System.out.println(longestString);
ArrayList<String> convert = new ArrayList<String>();
for(String counter : dict)
convert.add(counter);
getInstance(convert, 0, input.length, 0, 0);
System.out.println("\n\n\n" + longestString);
}
private void getInstance(ArrayList<String> searching, int pos, int length, int starter, int currentI) {
int i = starter;
do{
ArrayList<String> matched = new ArrayList<String>();
for(String counter : searching) {
if(counter.length() > pos) {
if(counter.charAt(pos) == input[i]){
matched.add(counter);
}
}
}
if(matched.size() > 0) {
getInstance(matched, pos+1,length,(i+1)%length, i%length);
}
else if(currentI != i && matched.size() > 0) {
getInstance(searching,pos,length,(i+1)%length, i%length);
}
if(matched.size() > 0 && longestString.length() < matched.get(0).length()){
longestString = searching.get(0);
}
++i;
i %= length;
}while(i != currentI);
}
public static void main(String[] args) {
new Test();
}
}
编辑:你应该修复一下,我只是在那里发现了一个错误