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

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

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

示例 1:

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

输出:"fl"

示例 2:

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

输出:""

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

提示:

1 <= strs.length <= 200

0 <= strsi.length <= 200

strsi 如果非空,则仅由小写英文字母组成

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后,停止继续查找添加。

相关推荐
longlongzihan2 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
h_a_o777oah3 小时前
【树论】树链剖分:将树形结构转化为线性结构以处理树上路径问题(洛谷 P3384 附C++代码模板)
数据结构·算法·线段树·acm·树链剖分·树论·重链剖分
HEJOO93 小时前
指针的算术运算详解
java·数据结构·算法
Coder-magician3 小时前
《代码随想录》刷题打卡day47:并查集-part01
数据结构·算法·图论
垆边人似月.4 小时前
VLAN 资源池(100~200 分档)
数据结构·算法
程序员清风5 小时前
算法与数据结构入门:复杂度、数组与链表
数据结构·算法·链表
Rnan-prince7 小时前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂8 小时前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
Logic1018 小时前
C语言/数据结构排序题解:三个数的最大乘积——排序后比较两种候选情况
c语言·数据结构·数组·排序·时间复杂度·算法题·负数处理
殷色玫瑰10 小时前
C++ string类详解:常用接口、字符串操作与模拟实现
java·linux·c语言·开发语言·数据结构·c++