首页 文章

在Java中实现数据结构和有效搜索

提问于
浏览
0

我有一个关于数据结构和高效搜索的任务 . 第一个输入参数是一些包含字符串的大文本文件,每行都是一个新字符串 . 第二个输入参数是一些前缀 . 输出是在以给定前缀开头的大文件中找到的最短单词 . 所以,我使用了HashMap并使用每个字母作为键构建了一个Trie . 所以,我只是查看而不是迭代,这节省了时间和内存 . 唯一看起来对我不好的是搜索最短的单词 . 我的意思是现在我得到以给定前缀开头的单词列表 . 然后我搜索最短的迭代列表 . 有没有其他方法来获得最短的单词?任何建议如何让这更好,真的很感激,因为这是我生命中第一次与Trie合作 . 请看下面的代码:

TrieNode

class TrieNode {

HashMap<Character, TrieNode> child;

boolean isLast;

public TrieNode() {
    child = new HashMap<Character, TrieNode>();
    // Initialize all the Trie nodes with NULL
    for (char i = 'a'; i <= 'z'; i++)
        child.put(i, null);
    isLast = false;
}}

Trie

public class Trie {

TrieNode root = new TrieNode();
ArrayList<String> words = new ArrayList<>();

public void insertIntoTrie(ArrayList<String> newWords) {

    int n = newWords.size();
    for (int i = 0; i < n; i++) {
        insert(newWords.get(i));
    }}


public void getWordsList(TrieNode curNode,
                         String prefix) {

    if (curNode != null) {

        if (curNode.isLast)
            words.add(prefix);

        for (char i = 'a'; i <= 'z'; i++) {
            TrieNode nextNode = curNode.child.get(i);
            if (nextNode != null) {
                getWordsList(nextNode, prefix + i);
            }}}}


public void getShortest(String str) {
    TrieNode prevNode = root;
    TrieNode found = null;

    String prefix = "";
    int len = str.length();

    for (int i = 0; i < len; i++) {

        prefix += str.charAt(i);

        char lastChar = prefix.charAt(i);

        TrieNode curNode = prevNode.child.get(lastChar);
        found = curNode;

        if (curNode == null) {
            System.out.println("No Results Found!");
            i++;
            break;}
    prevNode = curNode; }

    getWordsList(found, prefix);

    if (words.size() != 0) {

        String shortestWord = words.get(0);

        for (int j = 1; j < words.size(); j++) {
            String nextWord = words.get(j);
            if (nextWord.compareTo(shortestWord) < 0) {
                shortestWord = nextWord;

            }}

        System.out.println("The shortest word is: " + shortestWord);
    }}}

1 回答

  • 0

    除非您需要保存所有相关单词,否则没有真正的理由将它们保存在HashMap中 . 而且,HashMap对迭代几乎没用,因为无论如何你都需要访问每个单词 . 对于您的具体问题,我建议使用简单的最小搜索,即搜索前缀,每次运行它时,只有当它比您当前存储的单词短时才保存 .

相关问题