一次读取时按长度对文件中的所有单词进行排序。 (爪哇)

2024-01-28

我的数据结构课的作业是找到从一个单词到另一个单词的最短路径。

即开始:流血 -> 混合 -> 金发 -> 结束:血液,成本为 3。

我得到了一个单词列表,我必须使用地图对其进行分组。在哪里:

键:单词的长度,值:具有该长度的所有单词的集合。

我已经完成了该程序,但我认为如果改变在地图中存储集合的方式,我可以提高性能。现在,我扫描文本文件并将每个单词存储到 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.");
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一次读取时按长度对文件中的所有单词进行排序。 (爪哇) 的相关文章

随机推荐