Leetcode ---- Trie topic

Source: Internet
Author: User

Leetcode ---- Trie topic

I. Implement Trie (Prefix Tree)

Question:

 

Implement a trieinsert,search, AndstartsWithMethods.

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

Analysis: this is a typical trie tree, see http://blog.csdn.net/lu597203933/article/details/44227431

Code:

 

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");


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.