LeetCode——720. 词典中最长的单词

词典中最长的单词

题目

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

若无答案,则返回空字符串。

题目传送门

思路

开辟一棵前缀树,然后,把每个单词都存放进去这棵前缀树。然后,去搜索这棵树,进行一个广搜的时候,每在同一层的节点的字符串长度一定是相等的,所以,我们只需要每次将同一层的队列的字符串拿出来就可以了!

代码

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public String longestWord(String[] words) {
        Trie trie = new Trie();
        int length = words.length;
        Queue<Trie> queue = new LinkedList<>(); //搜索队列
        for (int i=0;i<length;++i)
        {
            trie.insert(words[i]);
        }

        queue.add(trie);
        String ans = "";
        while (!queue.isEmpty())
        {
            int size = queue.size();
            ans=queue.peek().now; // 因为要求最小字典序的字符串,而我们的数组是从a-z,所以这本身就是有顺序的,只需要第一个即可
            for (int i=0;i<size;++i)
            {
                Trie temp = queue.poll();
                for (Trie child : temp.children)
                {
                    if (child!=null && child.count>0) // 因为要求当前单词必须要由当前的数组中的字符串拼接起来,所以得加一个count>0,验证前面单词的连续性
                    {
                        queue.add(child);
                    }
                }
            }
        }
        return ans;
    }
}
class Trie{
    public Trie[] children;
    public int count;
    public String now;

    public Trie()
    {
        children= new Trie[26];
        count=0;
        now="";
    }

    public void insert(String word)
    {
        Trie root = this;               // 获得当前树
        int length = word.length();     // 获得等待插入单词的长度
        for (int i=0;i<length;++i)
        {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (root.children[index]==null)  // 如果当前结点为空,那么就创建结点
            {
                root.children[index] = new Trie();
            }
            root=root.children[index];
        }
        // 每次遍历完单词,要将当前结点的数值自增1,计算当前单词出现的频次
        ++root.count;
        // 记录下当前单词的完整形式
        root.now=word;
    }

    @Override
    public String toString() {
        return "Trie{" +
                "children=" + Arrays.toString(children) +
                ", count=" + count +
                ", now='" + now + '\'' +
                '}';
    }
}

结果

在这里插入图片描述
前缀树的再一次应用,就是那个要求当前单词必须由一个字母慢慢叠加而来那一块需要设计一下,还不错!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值