【发布时间】:2014-03-20 13:16:15
【问题描述】:
这是我的任务说明:
“构建一个程序,让用户根据随机字母结果创建不同的单词。 必须根据字典检查单词。”
这是目前为止的代码:
import java.util.Arrays;
public class AngloTrainer {
// ...
public AngloTrainer(String dictionaryFile) throws IOException {
// load dictionary?
//what else?
}
private String sort(String s){
//Sort the letters in a string.
char[] tecken = s.toCharArray();
String sorted = Arrays.sort(tecken);
return sorted;
}
// use this to verify loadDictionary
private void dumpDict() {
// Print out the dictionary at the screen.
// ... define!
}
private void loadDictionary( String fileName ) {
// Read the dictionary into a suitable container.
// The file is a simple text file. One word per line.
FileReader flr = new Filereader(fileName);
BufferedReader bfr = new BufferedReader(flr);
String line;
//collection/treeset?? maybe other??
while((line = bfr.readLine()) !=null ){
//save to a collention, but which?
}
}
private String randomLetters( int length ) {
// this makes vovels a little more likely
String letters = "aabcdeefghiijklmnoopqrstuuvwxyyz";
StringBuffer buf = new StringBuffer(length);
for ( int i = 0; i < length; i++ )
buf.append( letters.charAt(randomGenerator.nextInt(letters.length())));
return buf.toString();
}
/* Def. includes
* Let #(x,s) = the number of occurrences of the charcter x in the string s.
* includes(a,b) holds iff for every character x in b, #(x,b) <= #(x,a)
*
* A neccessary precondition for includes is that both strings are sorted
* in ascending order.
*/
private boolean includes( String a, String b ) {
if ( b == null || b.length() == 0 )
return true;
else if ( a == null || a.length() == 0 )
return false;
//precondition: a.length() > 0 && b.length() > 0
int i = 0, j = 0;
while ( j < b.length() ) {
if (i >= a.length() || b.charAt(j) < a.charAt(i))
return false;
else if (b.charAt(j) == a.charAt(i)) {
i++; j++;
} else if (b.charAt(j) > a.charAt(i))
i++;
}
//postcondition: j == b.length()
return true;
}
public static void main(String[] args) {
// ... define!
}
}
我应该为 loadDictionary 方法使用哪个集合? 正如作业所说,我需要根据字典集合检查我输入的单词。
【问题讨论】:
-
我建议你构建一个查找效率高的 trie!
-
你尝试过哪些收藏?当你尝试它们时发生了什么?
-
您已标记问题
hashset和treeset。您是否尝试过其中任何一种?
标签: java algorithm sorting hashset treeset