LeetCode-208.Implement Trie (Prefix Tree)

2846 단어 LeetCode
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;
}

좋은 웹페이지 즐겨찾기