您的位置:首页 > 其它

LeetCode-208.Implement Trie (Prefix Tree)

2016-07-16 12:46 211 查看
https://leetcode.com/problems/implement-trie-prefix-tree/

Implement a trie with 
insert
search
,
and 
startsWith
 methods.

Note:

You may assume that all inputs are consist of lowercase letters 
a-z
.
建立Trie树,一种数据结构,需要掌握。

class TrieNode
{
public:
// Initialize your data structure here.
TrieNode *children[26];
bool isWord;
TrieNode()
{
isWord = false;
for (auto &node : children)
node = NULL;
}
};

class Trie
{
public:
Trie()
{
root = new TrieNode();
}

// Inserts a word into the trie.
void insert(string word)
{
TrieNode *node = root;
for (char c : word)
{
if (!node->children[c - 'a'])
node->children[c - 'a'] = new TrieNode();
node = node->children[c - 'a'];
}
node->isWord = true;
}

// Returns if the word is in the trie.
bool search(string word)
{
TrieNode *node = root;
for (char c : word)
{
if (!node->children[c - 'a'])
return false;
node = node->children[c - 'a'];
}
return node->isWord;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix)
{
TrieNode *node = root;
for (char c : prefix)
{
if (!node->children[c - 'a'])
return false;
node = node->children[c - 'a'];
}
return true;
}

private:
TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");


相关链接

hihocoder:http://hihocoder.com/problemset/problem/1014

#include <string>
#include <iostream>
using namespace std;
struct TrieNode
{
TrieNode *children[26];
int count;
TrieNode()
{
count = 1;
for (auto &node : children)
node = NULL;
}
};

TrieNode* root;
void insert(string word)
{
TrieNode *node = root;
for (char c : word)
{
if (!node->children[c - 'a'])
node->children[c - 'a'] = new TrieNode();
else
node->children[c - 'a']->count++;
node = node->children[c - 'a'];
}
}

int startsWith(string prefix)
{
TrieNode *node = root;
for (char c : prefix)
{
if (!node->children[c - 'a'])
return 0;
node = node->children[c - 'a'];
}
return node->count;
}

int main()
{
root = new TrieNode();
int n, m;
string word;
cin >> n;
for (int i = 0; i<n; i++)
{
cin >> word;
insert(word);
}
cin >> m;
for (int i = 0; i<m; i++)
{
cin >> word;
cout << startsWith(word) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode trie