Leetcode-14. Longest Common Prefix

来源:互联网 发布:java whois 工具类 编辑:程序博客网 时间:2024/06/08 15:39

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


Analysis:
It’s an easy problem. First pieces of code is regular solution.
I try to use Trie (prefix tree) to solve the problem. Notice that, Trie is very helpful in prefix matching problem.

string longestCommonPrefix(vector<string>& strs) {   if (strs.empty()) return "";    string lcp = "";    int m = strs.size(), n = strs[0].size();    for (int i = 0; i < n; ++i){        for (int j = 1; j < m; ++j)            if (strs[j][i] != strs[0][i] || strs[j].size() == i)                return lcp;            lcp += strs[0][i];    }    return lcp;}

Using Trie data structure:

class TrieNode{public:    TrieNode* next[52];//upper and lower case    bool end_Word;     // end of a word    int sons;         // numbers of children    TrieNode() : end_Word(false), sons(0) //    {        for (int i = 0 ; i < 52; ++i)            next[i] = NULL;    }};class Trie{public:    TrieNode * root;    Trie ()    {        root = new TrieNode();    }    void insert(string word) {        TrieNode * p = root;        for (char c : word)        {            if (c >= 'a')            {                if (p -> next[c - 'a'] == NULL)                    {                        p -> next[c - 'a'] = new TrieNode();                        p -> sons ++; //                    }                p = p -> next[c - 'a'];            }            else            {                if (p -> next[c - 'A' + 26] == NULL)                    {                        p -> next[c - 'A' + 26] = new TrieNode();                        p -> sons ++;                    }                p = p -> next[c - 'A' + 26];                }        }        p -> end_Word = true;    }};class Solution {public:    string longestCommonPrefix(vector<string>& strs)     {        Trie T;        for(auto str : strs)            T.insert(str);        return findPrefix(T);    }private :    string findPrefix(Trie& T)    {        TrieNode* p = T.root;        string res = "";        int i = 0;        while (p -> sons == 1 && !p -> end_Word)        {            for (i = 0; i < 52; ++i)            {                if (p -> next[i])                {                    if (i < 26)                        res += char('a' + i);                    else                         res += char('A' + i - 26);                    break;                }            }            if (i == 52) break;            p = p -> next[i];        }        return res;    }};

Python code:

class Solution(object):    def longestCommonPrefix(self, strs):        """        :type strs: List[str]        :rtype: str        """        sz, ret = zip(*strs), ""          # zip('ABCD', 'xy') --> Ax By        for c in sz:            if len(set(c)) > 1: break            ret += c[0]        return ret
0 0
原创粉丝点击