首页 > 其他分享 >[leetcode 单词搜索]-[trie树]

[leetcode 单词搜索]-[trie树]

时间:2024-04-06 15:33:05浏览次数:18  
标签:Node traved curr trie 单词 int newx new leetcode

解法:
trie树

import java.util.*;

class Solution {
    int m, n;
    char[][] board;

    String[] querys;

    public static void main(String[] args) {
        Solution solution = new Solution();
        List<String> list = solution.findWords(new char[][]{
                {'o', 'a', 'a', 'n'}, {'e', 't', 'a', 'e'}, {'i', 'h', 'k', 'r'}, {'i', 'f', 'l', 'v'}
        }, new String[]{
                "oath", "pea", "eat", "rain"
        });

        for (String str : list) {
            System.out.println(str);
        }
    }

    Set<String> set = new TreeSet<>();

    public List<String> findWords(char[][] board, String[] words) {
        m = board.length;
        n = board[0].length;

        this.board = board;
        this.querys = words;

        int idx = 0;
        for (String word : words) {
            buildTree(word, idx++);
        }


        for (int x = 0; x < m; x++) {
            for (int y = 0; y < n; y++) {

                boolean[][] traved = new boolean[m][n];
                dfs(x, y, 1, traved, root);
            }
        }
//        return list.stream().map(STR::getStr).collect(Collectors.toList());
        return new ArrayList<>(set);
    }

    Node root;

    class Node {
        Node parent;
        Node[] children = new Node[26];
        int existIndex = -1;

        public Node() {
        }

        public Node(Node parent) {
            this.parent = parent;
        }
    }

    public void buildTree(String str, int index) {
        if (root == null) {
            root = new Node();
        }
        Node curr = root;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            Node child = curr.children[ch - 'a'];
            if (child == null) {
                curr.children[ch - 'a'] = new Node(curr);
            }
            if (i == str.length() - 1) {
                curr.children[ch - 'a'].existIndex = index;
            }
            curr = curr.children[ch - 'a'];
        }
    }

    public void dfs(int x, int y, int step,boolean[][] traved, Node parent) {
        Node curr = parent.children[board[x][y] - 'a'];
        if (curr == null) {
            return;
        }

        if (curr.existIndex > -1) {
            set.add(querys[curr.existIndex]);
        }

        traved[x][y] = true;

        int[][] dir = new int[][]{
                {1, 0}, {-1, 0},
                {0, 1}, {0, -1}
        };

        for (int i = 0; i < 4; i++) {
            int newx = x + dir[i][0];
            int newy = y + dir[i][1];

            if (newx >= 0 && newx < m && newy >= 0 && newy < n && !traved[newx][newy]) {
                traved[newx][newy] = true;
                dfs(newx, newy, step+1,traved, curr);
                traved[newx][newy] = false;
            }
        }
        traved[x][y] = false;
    }
}```

标签:Node,traved,curr,trie,单词,int,newx,new,leetcode
From: https://www.cnblogs.com/fishcanfly/p/18117481

相关文章

  • leetcode.206.反转链表
    题目题意:反转一个单链表。示例:输入:1->2->3->4->5->NULL输出:5->4->3->2->1->NULL思路双指针:创建指针p,curr,初始分别指向null和头节点,每轮循环移动一个节点的指向,直到指到最后一个位置为止。递归法:基于双指针。注意递归的退出条件实现双指针classSolution{......
  • leetcode.面试题 02.07. 链表相交
    题目给你两个单链表的头节点headA和headB,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回null。图示两个链表在节点c1开始相交:思路假a在链表A上移动,b在链表B上移动,a移动完在B上开始,b移动完再A上开始。最终a移动的距离a+c+x,b移动的距......
  • 【LeetCode刷题记录】简单篇-13-罗马数字转整数
    【题目描述】 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。字符数值I1V5X10L50C100D500M1000例如,罗马数字 2 写做 II ,即为两个并列的1。12 ......
  • Leetcode 无重复字符的最长子串
    powcai的滑动窗口解决问题:不断向后滑动窗口,出现重复元素,重新计算窗口,巧妙利用map来记录先前出现的元素的位置索引classSolution{publicintlengthOfLongestSubstring(Strings){//滑动窗口解决该问题intleft=0;intmax=0;Map......
  • Leetcode 412. Fizz Buzz
    给你一个整数n,找出从1到n各个整数的FizzBuzz表示,并用字符串数组answer(下标从1开始)返回结果,其中:answer[i]==“FizzBuzz”如果i同时是3和5的倍数。answer[i]==“Fizz”如果i是3的倍数。answer[i]==“Buzz”如果i是5的倍数。answer[i]......
  • LeetCode in Python 300. Longest Increasing Subsequence (最长递增子序列)
    求最长递增子序列是深度优先搜索(DFS)的一种应用,有两种比较好的方法可以解决。第一种是动态规划法,时间复杂度为O(n*n),即设置边界条件和更新迭代公式求解最优解。第二种使用二分查找将时间复杂度降为O(nlogn)。本文给出两种方法的实现代码及说明。示例:图1最长递增子序列输入......
  • LeetCode 13. 罗马数字转整数
    解题思路通过样例我们可以知道,将目标对应值和下一个目标对应值进行比较,如果小于,则sum=sum+目标对应值,如果大于,则sum=sum-目标对应值。最终的sum就是正确答案。相关代码classSolution{public:intromanToInt(strings){unordered_map<char,int>a;......
  • 单词 Play on Words
    原题链接题解我们将一个单词的首字母和尾字母看成两个结点,每个单词代表一条有向边。此时题意为:给你一个有向图,让你找到一条路径,使得仅仅只经过每条边一次。那么题意就是让我们求一个有向图的欧拉回路。code #include<bits/stdc++.h>usingnamespacestd;intfather[30]......
  • LeetCode-142. 环形链表 II【哈希表 链表 双指针】
    LeetCode-142.环形链表II【哈希表链表双指针】题目描述:解题思路一:快慢指针判断是否有环见解题思路二:set()解题思路三:0题目描述:给定一个链表的头节点head,返回链表开始入环的第一个节点。如果链表无环,则返回null。如果链表中有某个节点,可以通过连续跟踪next......
  • LeetCode 704.二分查找
    一、题目二、解题注:本文均是Java代码1、双闭区间写法classSolution{publicintsearch(int[]nums,inttarget){intleft=0,right=nums.length-1;while(left<=right){intmiddle=(left+right)>>>1;......