博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode----211. Add and Search Word - Data structure design
阅读量:4113 次
发布时间:2019-05-25

本文共 1850 字,大约阅读时间需要 6 分钟。

链接:

大意:

要求实现添加单词以及查找单词的数据结构及操作。其中,带查找的单词所含字符为'a'-'z'或者'.'。其中'.'可以代表任意一个小写字母。例子:

思路:

使用前缀树的数据结构:,只不过是需要多处理一种'.'的情况。当遇到'.'的时候,可以使用dfs依次遍历该node的所有children(最多26个children)。

若该node的所有children都无法使得其成为已添加的单词,则返回false。

若该node中的某一个child可以使其成为已添加的单词,则返回true。

代码:

class WordDictionary {    static class Node {        Node[] children = null;        boolean isWord;        public Node() {            children = new Node[26];        }    }    Node root = null;    /** Initialize your data structure here. */    public WordDictionary() {        root = new Node();    }        /** Adds a word into the data structure. */    public void addWord(String word) {        Node r = root;        for (char c : word.toCharArray()) {            if (r.children[c - 'a'] == null)                r.children[c - 'a'] = new Node();            r = r.children[c - 'a'];        }        r.isWord = true;    }        /** 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(word, 0, root);    }    // 基于dfs start为当前字符串的起始位置(使用start而不是用substring,更能提升效率)    public boolean search(String word, int start, Node r) {        while (start < word.length()) {            char c = word.charAt(start);            if (c != '.') {                if (r.children[c - 'a'] == null)                    return false;                r = r.children[c - 'a'];            } else {                for (Node node : r.children) {                    if (node != null) {                        if (search(word, start + 1, node))                            return true;                    }                }                // 这个'.'为任意字符都无法使得该字符串为已添加的字符串                return false;            }            start++;        }        return r.isWord;    }}

结果:

结论:

算是一个数据结构和算法结合的小demo了。。

转载地址:http://jaesi.baihongyu.com/

你可能感兴趣的文章
Mysql复制表以及复制数据库
查看>>
Kafka
查看>>
9.1 为我们的角色划分权限
查看>>
维吉尼亚之加解密及破解
查看>>
TCP/IP协议三次握手与四次握手流程解析
查看>>
PHP 扩展开发 : 编写一个hello world !
查看>>
inet_ntoa、 inet_aton、inet_addr
查看>>
用模板写单链表
查看>>
链表各类操作详解
查看>>
C++实现 简单 单链表
查看>>
Linux的SOCKET编程 简单演示
查看>>
Linux并发服务器编程之多线程并发服务器
查看>>
C语言内存检测
查看>>
Linux epoll模型
查看>>
Linux系统编程——线程池
查看>>
Linux C++线程池实例
查看>>
shared_ptr的一些尴尬
查看>>
C++总结8——shared_ptr和weak_ptr智能指针
查看>>
c++写时拷贝1
查看>>
Linux网络编程---I/O复用模型之poll
查看>>