hihoCoder#1014 Trie树

题目链接
最近发现hihoCoder上的题目都会用到比较单纯的数学结构和算法,不限LeetCode上那样,有些脑筋急转弯的感觉~
hihoCoder上的题目就像比赛那样,一般会给你一个场景,不同的是,他会在“小hi”和”小ho”的对话之中把模型给建立起来。

这一题就是普通的字典树,具体的介绍可以看维基百科
这篇博客里也有很好的介绍

AC的代码:

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<cstdlib>

using namespace std;
#define _length 11
struct TrieNode {
    int num;
    TrieNode* next[26];
    TrieNode() {
        num = 0;
        for(int i = 0;i < 26; ++i) {
            next[i] = NULL;
        }
    }
};

class TrieTree {
 public:
    TrieTree() {
        tree_head = new TrieNode;
    }
    void Insert(char* str);
    int Ask(char* str);
 private:
    TrieNode* tree_head;
};

void TrieTree::Insert(char* str) {
    TrieNode* temp = tree_head;
    for(int i = 0; str[i]; ++i) {
        int tmp = str[i] - 'a';
        if (temp->next[tmp] == NULL)
            temp->next[tmp] = new TrieNode;
        temp = temp->next[tmp];
        temp->num++;
    }
}

int TrieTree::Ask(char* str) {
    TrieNode* temp = tree_head;
    for(int i = 0; str[i]; ++i){
        int tmp = str[i] - 'a';
        if (temp->next[tmp]==NULL) return 0;
            temp = temp->next[tmp];
    }
    return temp -> num;
}

int main (int args, char* argv[])
{
    //freopen("F:/in.txt","r",stdin);
    int words_count, ask_count;
    scanf("%d", &words_count);
    TrieTree mytree;
    char word[_length];
    for(int i =0; i< words_count; i++) {
        cin >> word;
        mytree.Insert(word);
    }

    cin >> ask_count;
    char str[_length];
  for (int i = 0; i < ask_count; ++i) {
        cin >> str;
        int num = mytree.Ask(str);
        cout << num << endl;
  }
    //fclose(stdin);
    return 0;
}

这里我一开始偷懒,把里面的char字符数组 用string类型代替,可是一直内存泄露,弄得我崩溃。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值