【数据结构-字典树】力扣14. 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""。

示例 1:

输入:strs = ["flower","flow","flight"]

输出:"fl"

示例 2:

输入:strs = ["dog","racecar","car"]

输出:""

解释:输入不存在公共前缀。

提示:

1 <= strs.length <= 200

0 <= strs[i].length <= 200

strs[i] 如果非空,则仅由小写英文字母组成

csharp 复制代码
class Solution {
private:
    struct dt { 
        vector<dt*> children;
        bool isEnd;
        dt() : children(26, nullptr), isEnd(false) {}
    };
    dt* root;
public:
    Solution() {
        root = new dt();  // 初始化根节点
    }
    string longestCommonPrefix(vector<string>& strs) {
        for(string word : strs){
            if(word.empty()) return "";
            add(word);
        }
        
        string res = "";
        dt* node = root;
        while(true){
            int count = 0;
            int lastChild = -1;
            for(int i = 0; i < 26; i++){
                if(node->children[i] != nullptr){
                    count++;
                    lastChild = i;
                }
            }
            if(count != 1) break;
            if(node->children[lastChild]->isEnd){
                res += (lastChild + 'a');
                break;
            }
            res += (lastChild + 'a');
            node = node->children[lastChild];
        }
        return res;
    }

    void add(string word){
        dt* node = root;
        for(char ch : word){
            ch -= 'a';
            if(node->children[ch] == nullptr){
                node->children[ch] = new dt();
            }
            node = node->children[ch];
        }
        node->isEnd = true;
    }
};

我们可以使用tried树来解决这道题,首先先将所有strs的word构造出一个字典树。接下来我们从字典树的根节点不断向下查找,我们看他有几个子节点,如果有多个子节点,就说明不需要继续添加字符了,因为只有当children的数量为1个的时候,说明是公共前缀。

然后我们还要检查我们选择的下一个节点是不是某个word的结尾,如果是的话,就将其添加到res后,停止继续查找添加。

相关推荐
iAkuya21 小时前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
近津薪荼1 天前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
松☆1 天前
Dart 中的常用数据类型详解(含 String、数字类型、List、Map 与 dynamic) ------(2)
数据结构·list
历程里程碑1 天前
Linux15 进程二
linux·运维·服务器·开发语言·数据结构·c++·笔记
嵌入小生0071 天前
双向链表、双向循环链表之间的异同---嵌入式入门---Linux
linux·c语言·数据结构·链表·嵌入式·小白
独自破碎E1 天前
【滑动窗口+计数】LCR015找到字符串中所有字母异位词
数据结构·算法
BoJerry7771 天前
数据结构——单链表(不带头)【C】
c语言·开发语言·数据结构
-Try hard-1 天前
数据结构 | 双向链表、双向循环链表、栈
数据结构·链表·vim
想进个大厂1 天前
代码随想录day31 贪心05
数据结构·算法·leetcode
yyy(十一月限定版)1 天前
寒假集训1——暴力和枚举
数据结构·算法