Leetcode_212_单词搜索二_前缀树

该博客介绍了一个Java实现的解决方案,用于在一个二维字符矩阵中查找给定单词列表中的单词。它利用了深度优先搜索(DFS)策略,并通过一个链表结构维护字母之间的连接。在搜索过程中,遇到匹配的单词会将其添加到结果列表中,并对已访问过的单元格进行标记以避免重复。最后,返回找到的所有单词。
import java.util.*;

class ListNode {
    // 结尾标记,对应words中的第i个字符串,若为-1则代表不存在字符串;
    int flag;
    // 可以考虑更换成ListNode[26],并且让flag=-2表示存在子节点
    Map<Character, ListNode> next;

    public ListNode() {
        flag = -1;
        next = new HashMap<>();
    }
}

class Solution {
    ListNode head;
    char[][] board;
    List<String> ans;
    String[] words;
    static int[][] direction = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
    int m;
    int n;

    public List<String> findWords(char[][] board, String[] words) {
        ans = new ArrayList<>();
        head = new ListNode();
        this.words = words;
        int len = words.length;
        m = board.length;
        n = board[0].length;
        this.board = board;

        for (int i = 0; i < len; i++) {
            int len2 = words[i].length();
            ListNode temp = head;
            for (int j = 0; j < len2; j++) {
                ListNode next;
                if (!temp.next.containsKey(words[i].charAt(j))) {
                    next = new ListNode();
                    temp.next.put(words[i].charAt(j), next);
                } else {
                    next = temp.next.get(words[i].charAt(j));
                }
                temp = next;
            }
            temp.flag = i;
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(i, j, head);
            }
        }
        return ans;
    }

    void dfs(int i, int j, ListNode temp) {
        if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] == '#' || !temp.next.containsKey(board[i][j])) {
            return;
        }
        temp = temp.next.get(board[i][j]);
        char bef = board[i][j];
        board[i][j] = '#';
        if (temp.flag >= 0) {
            ans.add(words[temp.flag]);
            // 避免添加重复答案,取消结尾标记
            temp.flag = -1;
        }
        for (int[] dir : direction) {
            dfs(i + dir[0], j + dir[1], temp);
        }
        // 回溯
        board[i][j] = bef;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值