38. 2014年4月1日的360搜索广告部面试题

360的总部在北京望京798附近,这周有朋友去面试了,讲了下大致过程。


360总部一楼有个大厅,前台有很多MM,说明来意,被指向面试区(人还挺多的,应该很缺人,或者有新项目)。


一面:

技术面,是个小弟面的。

1)介绍下自己

2)说了几个重要的项目,问了些项目的情况,这都是面试官感兴趣的话题。

3)出了个编程题:设计一个trie树,实现创建 trie树和检索功能,数据为一批英文单词,都是小写字母。

分析:

这题目主要是三个方面,第一是设计trie树的数据结构,第二是实现trie树创建函数,第三是检索英文单词,看是否存在。


实现如下:

#include<iostream>
#include<string.h>
using namespace std;

#define MAXNODE 26
struct TrieNode{
        int counts;
        TrieNode* next[MAXNODE];//next character
        TrieNode():counts(1){
                int i = 0;
                while(i < MAXNODE)
                {
                        next[i++] = NULL;
                }
        }
};
void createTrie(TrieNode* &root, char* str)
{
        if(strlen(str) <= 0) return;
        if(root == NULL)
                root = new TrieNode();
        int i = 0;
        TrieNode* p = root;

        while(i < strlen(str))
        {
                int k = str[i++] - 'a';
                if(p->next[k])
                {
                        p->next[k]->counts ++;
                }
                else
                        p->next[k] = new TrieNode();
                p = p->next[k];
        }
}

int SearchTrie(TrieNode* root, char* str)
{
        TrieNode* p = root;
        if(p == NULL) return -1;
        int i = 0;
        while(i < strlen(str))
        {
                int k = str[i++] - 'a';
                if(p->next[k] == NULL)
                        return 0;
                else
                        p = p->next[k];
                if(i == strlen(str))
                        return p->counts;
        }
}

int main()
{
        char a[][4] = {"abc", "bcd", "ade", "acd", "bgf"};
        int i = 0;
        int j = 0;
        TrieNode* root = NULL;
        while(i < 5)
        {
                createTrie(root, a[i++]);
        }
        char* b = "bcd";
        int in = SearchTrie(root, b);
        if( in <= 0)
                cout << "Trie can't find \"" << b << "\"" << endl;
        else
                cout << "Trie have find \"" << b << "\"" << endl;
        return 0;
}

输出结果为:

Trie have find "bcd"


总结:

这个算法可以用于字符串的前缀查询,比如搜索TIPS等。




  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值