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

Description

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.


For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

问题描述

设计一个支持如下两个操作的数据结构

void addWord(word)
bool search(word)

search(word)可以搜索一个单词字面量或者只包含a- z和’.’的正则表达式。一个’.’可以表示任意字符
所有单词均为小写


问题分析

使用字典树来做,注意字典树节点存放isWord属性,标明该节点存在对应单词
addWord(word)向字典树中添加单词
search(word),遍历word和字典树,若遇到字符’.’,则回溯字典树当前节点的所有分支


解法(字典树)

class TrieNode {
    TrieNode[] children;
    boolean isWord;

    public TrieNode() {
        children = new TrieNode[26];
        isWord = false;
    }
}
public class WordDictionary {
    TrieNode root = null;

    public WordDictionary() {
        root = new TrieNode();
    }

    public void addWord(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()) {
            int j = c - 'a';
            if(node.children[j] == null) {
                node.children[j] = new TrieNode();
            }
            node = node.children[j];
        }
        node.isWord = true;
    }

    public boolean search(String word) {
        return find(word, root, 0);
    }

    private boolean find(String word, TrieNode node, int index) {
        //若到达word末尾,判断字典树当前节点是否有对应字符串
        if(index == word.length()) return node.isWord;
        if(word.charAt(index) == '.') {
            //回溯该节点所有分支
            for(TrieNode temp : node.children) {
                if(temp != null && find(word, temp, index+1)) return true;
            }
            return false;
        }else{
            int j = word.charAt(index) - 'a';
            TrieNode temp = node.children[j];
            return temp != null && find(word, temp, index+1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值