头条笔试第二题,最短前缀

头条笔试第二题,最短前缀

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

const int ALPHABET_SIZE = 26;

struct TrieNode
{
    struct TrieNode* children[ALPHABET_SIZE];
    int n;
};

TrieNode* init_node()
{
    TrieNode *pNode = new TrieNode;
    pNode->n = 0;
    for (int i=0; i<ALPHABET_SIZE; i++)
        pNode->children[i] = NULL;

    return pNode;
}

void insert(TrieNode* root, string key)
{
    TrieNode *pNode = root;

    for (int i=0; i<key.size(); i++) {
        int index = key[i] - 'a';
        if (NULL == pNode->children[index]) {
            pNode->children[index] = init_node();
        }
        pNode->n = pNode->n + 1;
        pNode = pNode->children[index];
    }
}

vector<string> shortest_prefix(vector<string>& strs)
{
    TrieNode *root = init_node();
    for (int i=0; i<strs.size(); i++)
        insert(root, strs[i]);

    int i, j, index;
    vector<string> prefix;
    TrieNode *pNode;
    for (i=0; i<strs.size(); i++) {
        pNode = root;
        for (j=0; j<strs[i].size(); j++) {
            index = strs[i][j] - 'a';
            if (pNode->children[index]->n <= 1)
                break;
            pNode = pNode->children[index];
        }
        prefix.push_back(strs[i].substr(0, j+1));
    }

    return prefix;
}

int main()
{
    vector<string> strs;
    strs.push_back("bytedance");
    strs.push_back("toutiaohao");
    strs.push_back("toutiaoapp");
    strs.push_back("iesac");
    strs.push_back("iestc");

    vector<string> ret = shortest_prefix(strs);
    for (int i=0; i<ret.size(); i++)
        cout << ret[i] << endl;

    /*
    cin >> n;
    for (int i=0; i<n; i++) {
        cin >> str;
        strs.push_back(str);
    }
    vector<string> ret = shortest_prefix(strs);
    for (int i=0; i<ret.size(); i++)
        cout << ret[i] << endl;
    */

    return 0;
}

仅供参考。

#笔试题目##字节跳动#
全部评论
def string_index(n, s_lst): res = [] for s in s_lst: copy_lst = s_lst.copy() copy_lst.remove(s) for i in range(1, len(s)): temp = s[:i] count = 0 for l in copy_lst: if temp != l[:i]: count += 1 if count == n - 1: res.append(temp) break return res if __name__ == "__main__": n = int(input()) s_lst = [] for i in range(n): s_lst.append(input()) res = string_index(n, s_lst) for s in res: print(s)
点赞 回复 分享
发布于 2018-09-20 21:46
一样的做法 0.2…
点赞 回复 分享
发布于 2018-09-20 21:41
我也是这样做的~~
点赞 回复 分享
发布于 2018-09-20 21:39
给力啊 我内存超了。。。才得到0.2
点赞 回复 分享
发布于 2018-09-20 21:38

相关推荐

白火同学:能。我当初应届沟通了1200,收简历50,面试10左右吧,加油投吧
点赞 评论 收藏
分享
群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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