Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

求解最长公共前缀,看到第一反应是用trie树,简历一颗trie树,然后查找下,某个点的计数次数是不是等于len,不等于则停止,等于则加入公共前缀字符串,继续查找。

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode(char v): val(v), count(0){
        for(int i = 0; i < 256; ++i)
            next[i] = NULL;
    }
    TrieNode *next[256];
    char val;
    int count;
};

class Trie {
public:
    Trie() {
        root = new TrieNode(' ');
    }
    
    TrieNode* createNode(char v)
    {
        TrieNode *newNode = new TrieNode(v);
        return newNode;
    }
    
    // Inserts a word into the trie.
    void insert(string word) {
        int len = word.size();
        TrieNode *tmpNode = root;
        for(int i = 0; i < len; ++i)
        {
            int tmp = word[i];
            if(tmpNode->next[tmp])
            {
                ++tmpNode->next[tmp]->count;
            }
            else
            {
                tmpNode->next[tmp] = createNode(word[i]);
                ++tmpNode->next[tmp]->count;
            }
            
            tmpNode = tmpNode->next[tmp];
        }
    }
    
    string longestCommonPrefix(int number)
    {
        string ans = "";
        TrieNode *tmpNode = root;
        while(NULL != tmpNode)
        {
            int count = 0, index = -1;
            for(int i = 0; i < 256; ++i)
            {
                if(NULL != tmpNode->next[i])
                {
                    ++count;
                    if(count >= 2)
                        break;
                    index = i;
                }
            }
            if(tmpNode != root && tmpNode->count == number)
                ans.push_back(tmpNode->val);
            if(count == 2 || (tmpNode != root && tmpNode->count != number))
                break;
            else
            {
                if(count == 0)
                    break;
                tmpNode = tmpNode->next[index];
            }
        }
        
        return ans;
    }
    
private:
    TrieNode* root;
};

class Solution {
public:
    //trie树, 构造一颗trie树,然后找到节点count不减少的节点,只要发现减少,
    //则说明该节点之前是公共前缀
    string longestCommonPrefix(vector<string>& strs) {
        int len = strs.size();
        string ans = "";
        if(len < 1)
            return ans;
        if(len == 1)
            return strs[0];
            
        Trie trie;
        for(int i = 0; i < len; ++i)
            trie.insert(strs[i]);
        return trie.longestCommonPrefix(len);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值