码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Implement Trie (Prefix Tree)

时间:2015-12-05 00:21:04      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

题目连接

https://leetcode.com/problems/implement-trie-prefix-tree/ 

Implement Trie (Prefix Tree)

Description

Implement a trie with insert, search, and startsWith methods.

字典树。。

class TrieNode {
public:
	// Initialize your data structure here.
	bool vis;
	TrieNode *ch[26];
	TrieNode() {
		vis = false;
		for (int i = 0; i < 26; i++) ch[i] = NULL;
	}
};

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

	// Inserts a word into the trie.
	void insert(string word) {
		if (word.empty()) return;
		TrieNode *x = root;
		int d = 0;
		Ite p = word.begin();
		while (p != word.end()) {
			d = *p - ‘a‘;
			if (!x->ch[d]) x->ch[d] = new TrieNode;
			x = x->ch[d];
			p++;
		}
		x->vis = true;
	}

	// Returns if the word is in the trie.
	bool search(string word) {
		TrieNode *x = root;
		int d = 0;
		Ite p = word.begin();
		while (p != word.end()) {
			d = *p - ‘a‘;
			if (!x || !x->ch[d]) return false;
			x = x->ch[d];
			p++;
		}
		return x->vis;
	}

	// Returns if there is any word in the trie
	// that starts with the given prefix.
	bool startsWith(string prefix) {
		TrieNode *x = root;
		int d = 0;
		Ite p = prefix.begin();
		while (p != prefix.end()) {
			d = *p - ‘a‘;
			if (!x || !x->ch[d]) return false;
			x = x->ch[d];
			p++;
		}
		return x != NULL;
	}

private:
	TrieNode* root;
	typedef string::iterator Ite;
};

leetcode Implement Trie (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/GadyPu/p/5020738.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!