题解 | #最长公共前缀#

最长公共前缀

http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

我以为是用前缀树,结果超内存,累了

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;


class preTreeNode{
public:
    preTreeNode(int path,int end):path(path),end(end){}
public:
    preTreeNode* index[26] = {nullptr};
    int path = 0;
    int end = 0;
};


class PreTree{
public:
    void insert(string& word){
        preTreeNode* curr = root;
        for(int i = 0;i<word.size();++i){
            int t = int(word[i]-'a');
            if(curr->index[t]==nullptr){
                curr->index[t] = new preTreeNode(1,0);
            }
            else{
                curr->index[t]->path++;
            }
            if(i==word.size()-1){
                curr->index[t]->end++;
            }
            curr = curr->index[t];                                                                                                                                                                                   
        }
    }
    string findmaxPre(int size,string& str){
        string result = "";
        preTreeNode* curr = root;
        for(int i = 0;i<str.size();++i){
            int in = int(str[i]-'a');
            if(curr->index[in]->path==size){
                result += str[i];
            }
            else{
                break;
            }
            curr = curr->index[in];
        }
        return result;
    }
public:
    preTreeNode* root = new preTreeNode(0,0);
};


class Solution {
public:
    /**
     * 
     * @param strs string字符串vector 
     * @return string字符串
     */
    string longestCommonPrefix(vector<string>& strs) {
        // write code here
        if(strs.empty()){
            return "";
        }
        PreTree P;
        for(int i = 0;i<strs.size();++i){
            P.insert(strs[i]);
        }
        return P.findmaxPre(strs.size(),strs[0]);
    }
};


int main(){
    Solution S;
    vector<string> v = {"abca","abc","abca","abc","abcc"};
    cout<<S.longestCommonPrefix(v)<<endl;
}
全部评论

相关推荐

白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
Cl_Wg:看牛客匿名贴容易抑郁,白菜就是我的天花板
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务