leetcode720——Longest Word in Dictionary

本文介绍了一种高效的方法来寻找字典中最长的单词,该单词可以通过字典中的其他单词逐字母生成。主要讨论了两种实现方式:使用集合和使用Trie树,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:给出字典中的一些字符串,找出他们中的最长单词,使得这个单词由字典中的字符串逐字母生成,如果长度相同取字典序较小的一个。

分析:trie应用。或者用集合set来做。

          方法一集合:字符串sort排序后是按长度由小到大,字典序由小到大排列的。取出words中的一个字符串,如果它长度为1或者取出它的长度减一的子串在built集合中,就更新答案,并将当前取出的字符串放入built集合中。built集合相当于一个满足我们题意要求的字符串集合,也就是里面插入的字符串都是逐个字母堆砌出来的。

代码:

方法一:集合 转载自http://blog.youkuaiyun.com/zy2317878/article/details/79056154

class Solution {
public:
    string longestWord(vector<string>& words) {
        sort(words.begin(), words.end());
        unordered_set<string> built;
        string res;
        for (string w : words) {
            if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) { //substr(0,n)从0起取多少个字符
                res = w.size() > res.size() ? w : res;
                built.insert(w);
            }
        }
        return res;
    }
};

方法二:trie JAVA代码转载自https://leetcode.com/problems/longest-word-in-dictionary/solution/

 

class Solution {
    public String longestWord(String[] words) {
        Trie trie = new Trie();
        int index = 0;
        for (String word: words) {
            trie.insert(word, ++index); //indexed by 1
        }
        trie.words = words;
        return trie.dfs();
    }
}
class Node {
    char c;
    HashMap<Character, Node> children = new HashMap();
    int end;
    public Node(char c){
        this.c = c;
    }
}

class Trie {
    Node root;
    String[] words;
    public Trie() {
        root = new Node('0');
    }

    public void insert(String word, int index) {
        Node cur = root;
        for (char c: word.toCharArray()) {
            cur.children.putIfAbsent(c, new Node(c));
            cur = cur.children.get(c);
        }
        cur.end = index;
    }

    public String dfs() {
        String ans = "";
        Stack<Node> stack = new Stack();
        stack.push(root);
        while (!stack.empty()) {
            Node node = stack.pop();
            if (node.end > 0 || node == root) {
                if (node != root) {
                    String word = words[node.end - 1];
                    if (word.length() > ans.length() ||
                            word.length() == ans.length() && word.compareTo(ans) < 0) {
                        ans = word;
                    }
                }
                for (Node nei: node.children.values()) {
                    stack.push(nei);
                }
            }
        }
        return ans;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值