首页 > 其他 > 详细

leetcode Implement Trie (Prefix Tree)

时间:2015-12-05 00:20:57      阅读:243      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!