LeetCode-208.Implement Trie (Prefix Tree)

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

Implement a trie with insertsearch, 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 
#include 
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> word;
        insert(word);
    }
    cin >> m;
    for (int i = 0; i> word;
        cout << startsWith(word) << endl;
    }
    return 0;
}


你可能感兴趣的:(LeetCode)