算法小知识----11.16----添加与搜索单词

137 阅读2分钟

这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战

添加与搜索单词

该题出自力扣的211题——添加与搜索单词,题解是自己做的

审题

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary :

WordDictionary() 初始化词典对象 void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配 bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。

  • 这次是实现一个类,类里面要有两种方法可以被调用,一种是新增,一种是搜索

  • 其实这题跟之前做过的前缀树是差不多的实现;利用前缀树的结构去实现,唯一需要额外做校验的就是有一个模糊查询的‘ . ’

  • 前缀树的话就是用对象作为数组,以当前的对象作为起点,树状展开,每一个字符都是作为一个节点

  • 新增的话:利用Assic值去作为字符的下标,存在则覆盖,不存在则new 出对象

  • 搜索:

    • 利用递归的方式去遍历数组和指定字符串
    • 其中如果有 ‘ . ’的话,也就是一个模糊查询的功能,就需要遍历所有的子树,并且其下的所有节点

编码

public class WordDictionary {
​
    private WordDictionary[] child;
    private boolean isEnd;
    public WordDictionary() {
        child = new WordDictionary[26];
        isEnd = false;
    }
​
    public void addWord(String word) {
        WordDictionary node = this;
        for (int i =0;i<word.length();i++){
            char c = word.charAt(i);
            int index = c-'a';
            if (node.child[index] == null){
                node.child[index] = new WordDictionary();
            }
            node = node.child[index];
        }
        node.isEnd = true;
    }
​
    public boolean search(String word) {
        WordDictionary node = this;
        return searchByPoint(node,0,word);
    }
​
    public boolean searchByPoint(WordDictionary node,int index,String word){
        if (index == word.length()) {
            return node.isEnd;
        }
            char c = word.charAt(index);
            //如果存在'.'的话,需要遍历后面所有非空节点
            if ('.' == c){
                for (int i = 0; i < 26; i++) {
                    WordDictionary child = node.child[i];
                    if (child != null && searchByPoint(child,index+1,word)){
                        return true;
                    }
                }
            }else {
                int childIndex = c-'a';
                if (node.child[childIndex] != null && searchByPoint(node.child[childIndex],index+1,word)){
                    return true;
                }
            }
            return false;
​
    }
}

1636703682(1).jpg