跳转至

720.词典中最长的单词 (Medium)*

题目描述*

题目描述*

思路 & 代码*

这个题的意思应该就是找到最长的前缀在字典中的字符串。直接按照长度和字典序排序然后在构造的过程中判断是否符合条件即可。

class TrieNode {
public:
    bool isEnd;
    vector<TrieNode*> next;
    TrieNode() : isEnd(false), next(26, nullptr) {}
};

class Solution {
public:
    string longestWord(vector<string>& words) {
        int n = words.size();
        if(n == 0) {
            return "";
        }
        sort(words.begin(), words.end(), [&](const string& a, const string& b) -> int {
            return (a.length() == b.length() ? a < b : a.length() < b.length());
        });

        auto root = new TrieNode();
        string res;
        for(auto& word : words) {
            auto valid = true;
            auto cur = root;
            int len = word.length();
            for(int i = 0; i < len; i++) {
                if(cur->next[word[i] - 'a'] == nullptr) {
                    cur->next[word[i] - 'a'] = new TrieNode();
                }
                cur = cur->next[word[i] - 'a'];
                if(i < len - 1 && !cur->isEnd) {
                    valid = false;
                    break;
                }
            }
            if(valid) {
                cur->isEnd = true;
                if(len > res.length()) {
                    res = word;
                }
            }
        }
        return res;
    }
};

最后更新: July 23, 2022