剑指offer 专项突破版 64、神奇的字典

https://leetcode-cn.com/problems/US1pGT/

思路
  • 这个题思路有点妙 用递归函数来做~
  • 递归函数返回遍历至此是否符合题目中的条件,参数是字符串、遍历到的索引index,此时的前缀树的层root,以及是否更改
  • 如果root是null,证明没有该结点,所以返回false
  • 如果index和word.length()相等,那么说明遍历到最后一层了,只有此前修改过且这个结点的isWord是true,才能说明是一个可以替换的字符串
  • 下面的代码理解起来也比较简单~
import java.util.Arrays;

class Trie {
    class TrieNode {
        boolean isWord;
        TrieNode[] children;

        TrieNode() {
            children = new TrieNode[26];
        }
    }

    TrieNode root;

    Trie() {
        root = new TrieNode();
    }

    void buildDict(String s) {
        TrieNode cur = root;

        for (char ch : s.toCharArray()) {
            if (null == cur.children[ch - 'a'])
                cur.children[ch - 'a'] = new TrieNode();
            cur = cur.children[ch - 'a'];
        }
        cur.isWord = true;
    }

    boolean dfs(String word, TrieNode root, int index, boolean isChanged) {
        if (null == root)
            return false;
        if (index == word.length())
            return isChanged && root.isWord;

        boolean result = false;

        if (isChanged) {
            if (null != root.children[word.charAt(index) - 'a']) {
                return dfs(word, root.children[word.charAt(index) - 'a'], index + 1, true);
            } else
                return false;
        } else {
            for (int i = 0; i < 26; i++) {
                if (null != root.children[i]) {
                    if (word.charAt(index) - 'a' == i)
                        result |= dfs(word, root.children[i], index + 1, false);
                    else
                        result |= dfs(word, root.children[i], index + 1, true);
                }
            }
        }
        return result;
    }
}


public class MagicDictionary {

    Trie trie;
    /**
     * Initialize your data structure here.
     */
    public MagicDictionary() {
        trie = new Trie();
    }

    public void buildDict(String[] dictionary) {
        Arrays.stream(dictionary).toList().forEach(trie::buildDict);
    }

    public boolean search(String searchWord) {
        return trie.dfs(searchWord,trie.root,0,false);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值