【每日一題-leetcode】208.實現Trie前綴樹

208.實現Trie前綴樹

  1. 實現 Trie (前綴樹)

難度中等297

實現一個 Trie (前綴樹),包含 insert, search, 和 startsWith 這三個操作。

示例:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

在這裏插入圖片描述

/**
     1.Trie樹 是一個多路查找樹,用於比較字符之間快速查找  是一種用空間換時間的思想。
     2,主要實現 內部有一個Trie數組 初始化大小爲init_size 一個是否爲字符串終止的標記
       a.添加 將字符串轉換成字符數組,並將字符數組添加到對應的位置上。如果爲null 直接new
       b.查找 和 前綴查找類似  前綴查找不需要判斷是否爲終止符  而查找需要在return 的時候 判斷是否是終止符
    */
    private final int INIT_SIZE = 26;
    private Trie  [] ch = new Trie  [INIT_SIZE];
    private boolean isEndOfStr = false;
    public Trie() {}
    
    public void insert(String word) {
        Trie tmp = this;
        for(char ch : word.toCharArray()){
            if(tmp.ch[ch-'a'] == null){
                tmp.ch[ch-'a'] = new Trie(); 
            }
            tmp = tmp.ch[ch-'a'];
        }
        tmp.isEndOfStr = true;
    }
    
    public boolean search(String word) {
        Trie tmp = this;
        for(char ch : word.toCharArray()){
            if(tmp.ch[ch-'a'] == null){
                return false;
            }
            tmp = tmp.ch[ch-'a'];
        }
        return tmp.isEndOfStr == true ? true : false;
    }
    
    public boolean startsWith(String prefix) {
        Trie tmp = this;
        for(char ch: prefix.toCharArray()){
            if(tmp.ch[ch-'a'] == null){
                return false;
            }
            tmp = tmp.ch[ch-'a'];
        }
        return true;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章