Longest Common Prefix

来源:互联网 发布:极品飞车ola车数据 编辑:程序博客网 时间:2024/05/31 18:35

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