211. 添加与搜索单词 - 数据结构设计

https://leetcode.cn/problems/design-add-and-search-words-data-structure/description/?envType=study-plan-v2&envId=top-interview-150

思路:就是然我们设计一个字典树,和上一题基本一样,之前使用的是树的方式来构建字典树。

class Main{
    class WordDictionary {
        private WordDictionary[] children;
        private boolean isEnd;

        public WordDictionary() {
            this.children = new WordDictionary[26];
            this.isEnd = false;
        }

        public void addWord(String word) {
            WordDictionary node = this;
            for (int i = 0; i < word.length(); i++) {
                char ch = word.charAt(i);
                int index = ch - 'a';
                if (node.children[index] == null) {
                    node.children[index] = new WordDictionary();
                }
                node = node.children[index];
            }
            node.isEnd = true;
        }

        public boolean search(String word) {
            WordDictionary node = this;
            return search2(node, word, 0);
        }

        public boolean search2(WordDictionary node, String word, int index) {
            if(index == word.length()) {
                return node.isEnd;
            }
            //遇到'.' 的逻辑:遍历该层的所有非空节点只要所有情况中存在匹配情况就返回true(意思就是只有true才是终点)
            char ch = word.charAt(index);
            if(ch == '.') {
                for(WordDictionary child : node.children) {
                    if( child != null) {
                        if(search2(child, word, index + 1)) {
                            return true;
                        }
                    }
                }
            } else {
                if(node.children[ch - 'a'] != null && search2(node.children[ch - 'a'], word, index + 1)) {
                    return true;
                }
            }
            return false;
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        WordDictionary wordDictionary = main.new WordDictionary();
        wordDictionary.addWord("bad");
        wordDictionary.addWord("dad");
        wordDictionary.addWord("mad");
        System.out.println(wordDictionary.search("pad")); // return false
        System.out.println(wordDictionary.search("bad")); // return true
        System.out.println(wordDictionary.search(".ad")); // return true
        System.out.println(wordDictionary.search("b..")); // return true
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值