题目

地址: https://leetcode.com/problems/add-and-search-word-data-structure-design/

Add and Search Word - Data structure design
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.

Example:

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

Note:
You may assume that all words are consist of lowercase letters a-z.

DFS回溯解法

思路解析:
这里用到字典树的结构,参考维基百科Tire。
Map<Character, TrieNode> childMap来连接上下的字母,如果是完整单词则标识boolean isWord

  1. 增加单词解析
    从根节点root开始解析,如果childMap没有包含该key,则添加。把子节点指向当前节点。

  2. 查找单词解析
    1)如果查找到单词word末尾,则判断字典树当前节点是否为结束节点,如果是,则返回true;否则返回false。
    2)如果单词word为结束,而当前节点childMap是空,则返回false。
    3)如果word的当前字符是., 则遍历所有的子节点。
    4)如果word的当前字符, 在字典树中没找到,则返回false。
    5)如果word的当前字符,在字典树中找到,则找下个子节点。

package backtracking;// https://leetcode.com/problems/add-and-search-word-data-structure-design/import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;/*** Your WordDictionary object will be instantiated and called as such:* WordDictionary obj = new WordDictionary();* obj.addWord(word);* boolean param_2 = obj.search(word);*/
public class WordDictionary {private class TrieNode {private boolean isWord;private Map<Character, TrieNode> childMap;public TrieNode() {isWord = false;childMap = new HashMap<Character, TrieNode>();}}private TrieNode root;/** Initialize your data structure here. */public WordDictionary() {root = new TrieNode();}/** Adds a word into the data structure. */public void addWord(String word) {TrieNode curr = root;for (char c: word.toCharArray()) {if (!curr.childMap.containsKey(c)) {curr.childMap.put(c, new TrieNode());}curr = curr.childMap.get(c);}curr.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 dfs(word,0, root);}public boolean dfs(String word, int pos, TrieNode node) {// if the word has all been scanned, returnif (pos == word.length()) {return node.isWord;}// reach the leaf before finishing scanning the wordif (node.childMap.size() == 0) {return false;}Character c = word.charAt(pos);// if the character at current position is '.',// recursive check whether the remaining word is in the trieif (c == '.') {for (char item: node.childMap.keySet()) {if (dfs(word, pos + 1, node.childMap.get(item))) {return true;}}}// if character at position 'pos' is neither equal to the node nor '.', return falseif (!node.childMap.containsKey(c)) {return false;}// if character at current position matches the node,// recursively search the remaining wordreturn dfs(word, pos + 1, node.childMap.get(c));}public static void main(String[] args) {WordDictionary obj = new WordDictionary();obj.addWord("bad");obj.addWord("dad");obj.addWord("mad");obj.addWord("a");System.out.println(obj.search("pad"));System.out.println(obj.search("bad"));System.out.println(obj.search(".ad"));System.out.println(obj.search("b.."));//obj.search("pad") -> false//obj.search("bad") -> true//obj.search(".ad") -> true//obj.search("b..") -> true}
}

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/WordDictionary.java

参考

https://zh.wikipedia.org/wiki/Trie

算法:回溯十六 Add and Search Word添加并查找单词相关推荐

  1. 机器学习之MATLAB代码--IWOA_BILSTM(基于改进鲸鱼算法优化的BiLSTM预测算法)(十六)

    机器学习之MATLAB代码--IWOA_BILSTM基于改进鲸鱼算法优化的BiLSTM预测算法(十六) 代码 数据 结果 代码 1. %% 基于改进鲸鱼算法优化的BiLSTM预测算法 clear;cl ...

  2. JavaScript学习(二十六)—事件处理程序的添加与删除

    JavaScript学习(二十六)-事件处理程序的添加与删除 一.什么是事件? 所谓事件就是指用户或页面自身的某些行为,如点击鼠标,敲击键盘都是属于事件. 二.事件处理程序 当事件被触发时会引起某些程 ...

  3. IDA*算法解十六宫格拼图问题

    IDA*算法, ID(Iterative Deepening)指的是迭代加深. 它的思想是重复进行限制最大深度的深度优先搜索(此限制从某个最小值遍历到最大值), 也称为深度受限搜索. 一般情况下, 为 ...

  4. leetcode 211. Add and Search Word - Data structure design Trie树

    题目链接 写一个数据结构, 支持两种操作. 加入一个字符串, 查找一个字符串是否存在.查找的时候, '.'可以代表任意一个字符. 显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可 ...

  5. LeetCode Add and Search Word - Data structure design(字典树)

    问题:设计一个支持addWord,search查询的数据结构,要求search支持.正则查询 思路:使用Trie数据结构,在匹配.时,从子结点中选取可行的一个继续匹配下一个字符,主要思路是基于递归 具 ...

  6. leetcode Add and Search Word - Data structure design

    我要在这里装个逼啦 class WordDictionary(object):def __init__(self):"""initialize your data str ...

  7. 斗地主AI算法——第十六章の样例分析

    上一章,我们已经完成了测试模块的开发.至此我们已经可以进行整体测试了.本章主要内容就是对随机生成的对局情况进行简单的分析. 实际上整个开发过程绝大部分时间都是用在样例分析上,通过样例给出的返回操作分析 ...

  8. 前景检测算法(十六)--背景减除结束篇

    说实话,没打算做视频监控这一块,只是因为目标检测中看到了前景提取这一块,跟着学习了下,到此为止吧.mark个算法库及相关测试. 1.前景提取测试库: http://blog.csdn.net/frd2 ...

  9. 机器学习之经典算法(十六) Birch算法

    (一)  Birch算法简介: BIRCH(Balanced Iterative Reducing and Clustering Using Hierarchies)全称是:利用层次方法的平衡迭代规约 ...

  10. 数据结构和算法三十六

    剑指 Offer 66. 构建乘积数组 题目:给定一个数组 A[0,1,-,n-1],请构建一个数组 B[0,1,-,n-1],其中 B[i] 的值是数组 A 中除了下标 i 以外的元素的积, 即 B ...

最新文章

  1. luogu P1037 【产生数】
  2. dash plotly
  3. hushen 300
  4. 使用RNN解决NLP中序列标注问题的通用优化思路
  5. 文献学习(part71)--Graph Regularized Non-negative Matrix Factorization for Data Representation
  6. linux下统计文件的数目,Linux下如何统计文件数目
  7. linux 安装 中文输入法,[linux]安装中文输入法
  8. hive外部表改为内部表_Hive基础之创建表
  9. FFmpeg+dxva2 H265硬解码 下方出现绿条或被下方拉长
  10. 计算机网络flash实训报告,flash动画实训总结精选 .doc
  11. Resolver error Error Downloading VS Code Server failed - please install either curl or wget on the
  12. 信签纸有虚线怎么写_信签纸写作文格式怎么用
  13. 2.4. Prompting
  14. 移动CRM产品同质化严重,市场一片红海
  15. 个人练习小览---《微金所仿站》
  16. HDU-5514 Frogs
  17. 使用frp配置内网穿透
  18. 未来两年前装激光雷达规模超150万颗,技术路线博弈下的市场
  19. 正版推荐 - Hard Disk Sentinel Pro 专业版硬盘检测工具软件
  20. 牛客小白月赛53(A-E)

热门文章

  1. 可由一个尾指针唯一确定的链表有_六十九、数据结构链表的实现
  2. Asp.Net客户端触发服务器端事件及_dopostback
  3. 数字信号处理实验(六)——FIR滤波器的设计
  4. MySQL移动数据目录出现权限问题
  5. 《Java技术》预备作业总结
  6. android 技术点记录
  7. C++对象数组的实例学习
  8. 前端项目构建工具---Grunt
  9. VMware OSP对比VMware Tools:简化Linux驱动更新
  10. wordpress自定义打赏