程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode ----Trie專題

leetcode ----Trie專題

編輯:C++入門知識

leetcode ----Trie專題


一:Implement Trie (Prefix Tree)

題目:

 

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

Note:
You may assume that all inputs are consist of lowercase letters a-z.

分析:此題是典型的trie樹,可以參見:http://blog.csdn.net/lu597203933/article/details/44227431

代碼:

 

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

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

    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *p = root;
        for(int i = 0; i < s.size(); i++){
            if(p->next[s[i]-'a'] == NULL){
                p->next[s[i]-'a'] = new TrieNode();
            }
            p = p->next[s[i]-'a'];
        }
        p->isString = true;
    }

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

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

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved