[LeetCode-JAVA] Implement Trie (Prefix Tree)

來源:互聯網
上載者:User

標籤:

題目:

Implement a trie with insertsearch, and startsWith methods.

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

思路:

題目的內容是實現一個首碼樹,用來儲存string的,因此可以理解為一個26叉樹,為了儲存每一個節點的孩子,用hashmap來進行儲存。

同時回顧首碼樹的概念,除了內容為一個字元外,每一個節點還應有一個標誌位,是否為已經查過的(即添加的)單詞。

insert:分析單詞的每一個字元,如果存在與已經有的孩子中,則迴圈轉到該孩子節點,否則建立孩子節點,最後在單詞的末尾字元isWord標誌位true;

search: 逐個分析每個字元,如果不存在該字元的孩子則返回false,否則迴圈之後,查看末尾字元的標誌位即可;

pifix: 和search一樣,只是在最後只要是都存在每個字元相應的孩子map,則返回true。

代碼:

class TrieNode {    // Initialize your data structure here.    boolean isWord;    HashMap<Character, TrieNode> map;    public TrieNode() {        map = new HashMap<Character, TrieNode>();    }}public class Trie {    private TrieNode root;    public Trie() {        root = new TrieNode();    }    // Inserts a word into the trie.    public void insert(String word) {        char[] charray = word.toCharArray();        TrieNode temp = root;        for(int i = 0 ; i < charray.length ; i++){            if(!temp.map.containsKey(charray[i]))                temp.map.put(charray[i], new TrieNode()); //添加            temp = temp.map.get(charray[i]); //轉到孩子節點            if(i == charray.length - 1) //末尾字元                temp.isWord = true;        }    }    // Returns if the word is in the trie.    public boolean search(String word) {        TrieNode temp = root;                for(int i = 0 ; i < word.length() ; i++){            TrieNode next = temp.map.get(word.charAt(i));            if(next == null)                return false;            temp = next;        }        return temp.isWord;    }    // Returns if there is any word in the trie    // that starts with the given prefix.    public boolean startsWith(String prefix) {        TrieNode temp = root;                for(int i = 0 ; i < prefix.length() ; i++){            TrieNode next = temp.map.get(prefix.charAt(i));            if(next == null)                return false;            temp = next;        }        return true;    }}

參考連結:http://www.bubuko.com/infodetail-807921.html

[LeetCode-JAVA] Implement Trie (Prefix Tree)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.