题解 | #最长公共前缀#

最长公共前缀

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

相关推荐

头像
11-09 17:30
门头沟学院 Java
TYUT太摆金星:我也是,好几个华为的社招找我了
点赞 评论 收藏
分享
过往烟沉:我说什么来着,java就业面就是广!
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务