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;
        
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章