LeetCode算法練習——字典樹(一)

字典樹

       又稱單詞查找樹,Trie樹,是一種樹形結構,是一種哈希樹的變種。典型應用是用於統計,排序和保存大量的字符串(但不僅限於字符串),所以經常被搜索引擎系統用於文本詞頻統計。它的優點是:利用字符串的公共前綴來減少查詢時間,最大限度地減少無謂的字符串比較,查詢效率比哈希樹高。

字典樹的性質:

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

LeetCode208. 實現 Trie (前綴樹)

實現一個 Trie (前綴樹),包含 insertsearch, 和 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

此題的目的就是了解字典樹的基本操作,完整代碼如下:

class Trie{
public:
	struct Node{
    	bool isWord = false;
    	string word; // 加入存儲單詞節點
    	Node* next[26];
	};
    Node* root;
    Trie(){
        this->root = new Node();
    }
    //插入
    void insert(string word){
        Node* prefix = root;
        for(int i = 0; i < word.size(); i++){
            if(prefix->next[word[i] - 'a'] == nullptr)
                prefix->next[word[i] - 'a'] = new Node();
            prefix = prefix->next[word[i] - 'a'];
        }
        if(!prefix->isWord){
            prefix->isWord = true;
            prefix->word = word;
        }
    }
    //搜索
    bool search(string word){
        Node* prefix = root;
        for(char ch : word){
            if(prefix->next[ch - 'a'] == nullptr)
                return false;
            prefix = prefix->next[ch - 'a'];
        }
        return prefix->isWord;
    }
    //前綴是否匹配
    bool startsWith(string word){
	Node* prefix = root;
	for(char ch : word){
            if(prefix->next[ch - 'a'] == nullptr)
                return false;
            prefix = prefix->next[ch - 'a'];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

LeetCode212.  單詞搜索2

給定一個二維網格 board 和一個字典中的單詞列表 words,找出所有同時在二維網格和字典中出現的單詞。

單詞必須按照字母順序,通過相鄰的單元格內的字母構成,其中“相鄰”單元格是那些水平相鄰或垂直相鄰的單元格。同一個單元格內的字母在一個單詞中不允許被重複使用。

示例:

輸入: 
words = ["oath","pea","eat","rain"] and board =
[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

輸出: ["eat","oath"]

此題的核心是用回溯思想做,但是如果在LeetCode79-單詞搜索1的基礎上加一個循環,暴力解決的話,會出現超時,因此需要對算法的時間複雜度進行優化,於是我們引入了字典樹的來優化單詞存儲遍歷的方式,套用LeetCode-208的字典樹模板代碼完成,完整代碼如下:

class Trie{
public:
	struct Node{
    	bool isWord = false;
    	string word; // 加入存儲單詞節點
    	Node* next[26];
	};
    Node* root;
    Trie(){
        this->root = new Node();
    }
    void insert(string& word){
        Node* prefix = root;
        for(int i = 0; i < word.size(); i++){
            if(prefix->next[word[i] - 'a'] == nullptr)
                prefix->next[word[i] - 'a'] = new Node();
            prefix = prefix->next[word[i] - 'a'];
        }
        if(!prefix->isWord){
            prefix->isWord = true;
            prefix->word = word;
        }
    }
};

class Solution {
private:
    int row, column;
    vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
    vector<vector<bool>> visited;
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        // DFS+Trie優化
        vector<string> res;
        row = board.size();
        if(row == 0)
            return res;
        column = board[0].size();
        if(column == 0)
            return res;
        Trie* T = new Trie();
        for(string &word: words){
            T->insert(word);
        }
        visited = vector<vector<bool>>(row, vector<bool>(column, false));
        // DFS
        for(int i = 0; i < row; ++i){
            for(int j = 0; j < column; ++j){
                Trie::Node* prefix = T->root;
                if(prefix->next[board[i][j]-'a'] != nullptr)
                    dfs(board, i, j, prefix->next[board[i][j]-'a'], res);
            }
        }
        return res;
    }

private:
    void dfs(const vector<vector<char>>& board, int i, int j, Trie::Node* prefix, vector<string>& res){
        if(prefix->isWord){
            if(count(res.begin(), res.end(), prefix->word)==0)
                res.push_back(prefix->word);
        }
        visited[i][j] = true;
        for(auto &d: dirs){
            int x = i + d[0];
            int y = j + d[1];
            if((0 <= x && x < row && 0 <= y && y < column) && !visited[x][y] && prefix->next[board[x][y] - 'a']!=nullptr){
                dfs(board, x, y, prefix->next[board[x][y] - 'a'], res);
            }
        }
        visited[i][j] = false;
    }
};

 

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