Leetcode 208. Implement Trie (Prefix Tree)

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

Example:

Trie trie = new Trie();

trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true

實現一個簡單的鍵樹

struct TrieNode{
	bool isWord;
	TrieNode* next[26];
	TrieNode() :isWord(false){ memset(next, 0, sizeof(next)); }
};

class Trie {
public:
	TrieNode* root;

	/** Initialize your data structure here. */
	Trie() {
		root = new TrieNode();
	}

	/** Inserts a word into the trie. */
	void insert(string word) {
		TrieNode* cur = root;
		for (char ch : word){
			TrieNode* node = cur->next[ch - 'a'];
			if (node == NULL){
				cur->next[ch - 'a'] = new TrieNode();
			}
			cur = cur->next[ch - 'a'];
		}

		if (!cur->isWord) cur->isWord = true;
	}

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

		return cur->isWord;
	}

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

		return true;
	}
};

summary

  1. 記住此鍵樹模板
發佈了93 篇原創文章 · 獲贊 9 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章