题解 | #最长公共前缀#

最长公共前缀

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;
}
全部评论

相关推荐

10-11 17:45
门头沟学院 Java
走吗:别怕 我以前也是这么认为 虽然一面就挂 但是颇有收获!
点赞 评论 收藏
分享
斑驳不同:还为啥暴躁 假的不骂你骂谁啊
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务