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

用单词查找树,实现方法有很多,但是看了算法第4版的实现发现代码真的简洁强大。

可以先看这篇文章:单词查找树

这里搜索单词只需要判断true或false,不需要全部匹配,稍稍修改了下。

class WordDictionary {

        private Node root;
        private static int R = 26;

        static class Node {
            private boolean isWordEnd = false;
            private Node[] next = new Node[R];
        }

        /**
         * Initialize your data structure here.
         */
        public WordDictionary() {
        }

        /**
         * Adds a word into the data structure.
         */
        public void addWord(String word) {
            root = put(root, word, 0);
        }

        private Node put(Node x, String word, int d) {
            if (x == null) {
                x = new Node();
            }
            if (d == word.length()) {
                x.isWordEnd = true;
                return x;
            }
            char c = word.charAt(d);
            x.next[c - 'a'] = put(x.next[c - 'a'], word, d + 1);
            return x;
        }

        /**
         * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
         */
        public boolean search(String word) {
            return search(root, word, 0);
        }

        private boolean search(Node x, String pat, int d) {
            if (x == null) {
                return false;
            }
            if (d == pat.length()) {
                return x.isWordEnd;
            }
            char c = pat.charAt(d);
            if (c == '.') {
                // 搜索所有节点
                for (int i = 0; i < R; i++) {
                    if (search(x.next[i], pat, d + 1)) {
                        return true;
                    }
                }
            } else {
                return search(x.next[c - 'a'], pat, d + 1);
            }
            return false;
        }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值