Leetcode 212. 單詞搜索 II

212. 單詞搜索 II
給定一個二維網格 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”]
說明:
你可以假設所有輸入都由小寫字母 a-z 組成。

學習自

首先使用對每一個board[i][j]使用dfs這沒意見吧?關鍵題目的測試用例有一種是words裏面都是前綴很像的詞,比如[aaaaab, aaaaac, aaaaad],那麼每次都需要從aaaaa開始就沒必要了,所以這裏使用前綴樹,對於前綴相同的word,就不需要每次都遍歷一邊,而是在遞歸遍歷前綴樹時,只在當前字符不同的時候再分道揚鑣。所以對於這種測試用例會變得巨他嗎快。

struct Node {
    bool word;
    string str;
    unordered_map<char, Node*> words;
};
class Trie {
public:
    Trie() {
        root = new Node();
    }
    void insert(string word) {
        Node* p = root;
        for (char c: word) {
            if (p->words.find(c) == p->words.end()) {
                Node* t = new Node();
                p->words[c] = t;
            } 
            p = p->words[c];
        }
        p->str = word; // node對應的word,爲了之後根據node來找到結果
        p->word = true;
    }
    void search(vector<string>& res, vector<vector<char>>& board) {
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[i].size(); j++) {
                help(res, board, root, i, j);
            }
        }
    }
    void help(vector<string>&res, vector<vector<char>>& board, Node* p, int x, int y) {
        if (p->word) {
            p->word = false; // 其他方向就不會再把答案放進去了
            res.push_back(p->str);
            return;
        } 
        if (x < 0 || x == board.size() || y < 0 || y == board[x].size()) return;
        if (p->words.find(board[x][y]) == p->words.end()) return;
        p = p->words[board[x][y]]; // 此時的p是其他字符了
        char cur = board[x][y];
        board[x][y] = '#';
        help(res, board, p, x+1, y);
        help(res, board, p, x-1, y);
        help(res, board, p, x, y+1);
        help(res, board, p, x, y-1);
        board[x][y] = cur;
    }
    
private:
    Node* root;
};
class Solution {
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        Trie trie;
        vector<string> res;
        for (string& w: words) {
            trie.insert(w);
        }
        trie.search(res, board);
        return res;
        
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章