我的数据结构课的作业是找到从一个词到另一个词的最短路径。
即开始:流血 -> 混合 -> 金色 -> 结束:血,成本为 3。
我得到了一个单词列表,我必须使用 map 对其进行分组。地点:
键:单词的长度,值:具有该长度的所有单词的集合。
我已经完成了这个程序,但我认为如果我改变我在 map 中存储集合的方式,我可以提高性能。现在我扫描文本文件并将每个单独的单词存储到一个 ArrayList 中,然后我遍历 ArrayList 并将所有长度为 x 的单词存储到一个集合中,同时从列表中删除每个单词。我从 ArrayList 中的第一个元素开始,直到列表为空。
我想知道我是否可以在读取文件时进行这种排序,并完全避免使用 ArrayList。
这是我的代码:
ArrayList<String> wordList = new ArrayList<String>();
Map<Integer, Set> setMap = new HashMap<Integer, Set>();
Graph pathGraph = new Graph();
private void readFile(String file) {
try {
FileReader f = new FileReader(file);
BufferedReader reader = new BufferedReader(f);
String line = "";
while ((line = reader.readLine()) != null) {
wordList.add(line);
}
} catch (Exception e) { //Done in case of an exception
System.out.println("No file found.");
}
}
private void mapMaker() {
int wordLength = 1;
Set<String> wordSet = new HashSet<String>();
while (!wordList.isEmpty()) {
wordSet = setBuilder(wordLength);
if (!wordSet.isEmpty()) {
setMap.put(wordLength, wordSet);
}
wordLength++;
}
}
private Set<String> setBuilder(int x) {
Set<String> wordSet = new HashSet<String>();
int counter = 0;
while (counter < wordList.size()) {
if (wordList.get(counter).length() == x) {
wordSet.add(wordList.get(counter));
wordList.remove(counter);
} else {
counter++;
}
}
return wordSet;
}
提前感谢您的任何意见。
最佳答案
private void readFile(String file) {
try {
FileReader f = new FileReader(file);
BufferedReader reader = new BufferedReader(f);
String word = "";
while ((word = reader.readLine()) != null) {
int length = word.length();
if(setMap.containsKey(length)) {
setMap.get(length).add(word);
} else {
Set set = new HashSet<String>();
set.add(word);
setMap.put(length, set);
}
}
} catch (Exception e) { //Done in case of an exception
System.out.println("No file found.");
}
}
关于java - 在一次读取中按长度对文件中的所有单词进行排序。 ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244627/