實現字典樹Trie的基本操作

字典樹:根節點不包含字符,除根節點外每一個節點都只包含一個字符; 從根節點到某一節點,路徑上經過的字符連接起來,爲該節點對應的字符串; 每個節點的所有子節點包含的字符都不相同。

實現字典樹的插入insert(),查找search(string key),判斷是否有以某字符串爲前綴的字符串starsWith(string s)。

實現代碼如下,可以將bool hasWord改爲一個int型來統計出現的詞頻。

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

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

    // Inserts a word into the trie.
    void insert(string s) {
		if(s.empty()) {
			return;
		}
        TrieNode *t = root->child[s[0]-'a'], *p=root;
		for(int i=0; i<s.size(); ++i) {
			if( t == NULL) {
				t=new TrieNode();
				t->data=s[i];
				p->child[s[i]-'a']=t;						
			}
			if( i+1 < s.size() ) {
				p=t;
				t=p->child[s[i+1]-'a'];
			}	
		}
		t->hasWord=true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
		if(key.empty()) {
			return false;
		}
        TrieNode *p=root, *t=p->child[ key[0]-'a' ];
		for(int i=0; i<key.size(); ++i) {
			if(t == NULL) {
				return false;
			}
			if( i+1 < key.size() ) {
				p=t;
				t=p->child[ key[i+1]-'a' ];
			}
		}
		if(t->hasWord == false){
			return false;
		}
		return true;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        if(prefix.empty()) {
			return false;
		}
        TrieNode *p=root, *t=p->child[ prefix[0]-'a' ];
		for(int i=0; i<prefix.size(); ++i) {
			if(t == NULL) {
				return false;
			}
			if( i+1 < prefix.size() ) {
				p=t;
				t=p->child[ prefix[i+1]-'a' ];
			}
		}
		return true;
    }

private:
    TrieNode* root;
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章