Leetcode-14. Longest Common Prefix

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值