【数据结构-字典树】力扣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后,停止继续查找添加。

相关推荐
思捻如枫2 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
GalaxyPokemon2 小时前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
小猫咪怎么会有坏心思呢2 小时前
华为OD机考 - 水仙花数 Ⅰ(2025B卷 100分)
数据结构·链表·华为od
hn小菜鸡3 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX3 小时前
分享今天做的力扣SQL题
sql·算法·leetcode
全栈凯哥6 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥6 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu6 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode
lyh13447 小时前
【SpringBoot自动化部署方法】
数据结构
蒟蒻小袁7 小时前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先