当前位置: 首页 > ops >正文

力扣面试150题--添加与搜索单词 - 数据结构设计

Day 68

题目描述

在这里插入图片描述

思路

根据昨天的trie前缀树进行修改,特殊需要考虑的点在于存在通配符,我来说明下如何解决这个问题的:
关键在于这段代码

 for (WordDictionary child : words.child) {if (child != null && find(child, word, i + 1)) {return true;}}return false;

遍历当前节点的所有非空子节点,对每个子节点递归调用 find 函数,处理剩余字符(start + 1)。
只要找到一条有效路径,立即返回 true。
如果所有子节点都无法匹配,返回 false。
做法

class WordDictionary {public WordDictionary[]child;public boolean isend;public WordDictionary() {child=new WordDictionary[27];isend=false;}public void addWord(String word) {WordDictionary words=this;for(int i=0;i<word.length();i++){char x=word.charAt(i);int index=x-'a';if(words.child[index]==null){words.child[index]=new WordDictionary();}words=words.child[index];}words.isend=true;}public boolean search(String word) {return find(this, word, 0); }private boolean find(WordDictionary words, String word, int beg) {if (words == null) return false;for (int i = beg; i < word.length(); i++) {char c = word.charAt(i);if (c == '.') {for (WordDictionary child : words.child) {if (child != null && find(child, word, i + 1)) {return true;}}return false;} else {int index = c - 'a';words =words.child[index];if (words == null) return false;}}return words.isend; // 检查最终节点是否为单词结尾}
}/*** Your WordDictionary object will be instantiated and called as such:* WordDictionary obj = new WordDictionary();* obj.addWord(word);* boolean param_2 = obj.search(word);*/
http://www.xdnf.cn/news/14207.html

相关文章:

  • Java延时
  • python中的模块化编程:日期模块、math算术模块、random模块
  • 温度对IO通信的影响
  • pythonday46
  • Python 标准库之 math 模块
  • 智慧水利可视化:水利水电工程数智化
  • 快速排序C++实现
  • IO扩展的一种简易方法
  • ECharts 图表生成示例
  • CentOS7报错:Cannot find a valid baseurl for repo: base/7/x86_64
  • day034-rsync异地容灾
  • org.springframework.cloud.openfeign 组件解释
  • JAVA实战开源项目:在线课程管理系统 (Vue+SpringBoot) 附源码
  • 超强人工智能解决方案套件InfiniSynapse:精准的业务理解、对各种数据源进行全模态联合智能分析--部署安装@Ubuntu22.04 @Docker
  • 【Z Arcade】八色部落战争各阵营兵种分析级排名
  • 【C语言练习】096. 使用C语言实现简单的游戏逻辑
  • RK AndroidFramework 内置应用可,卸载,恢复出厂设置恢复安装
  • 蓝桥杯国赛前一晚知识点准备(十六届python)
  • 多线程——锁
  • Keepalived 高可用
  • 基于SpringBoot+JSP开发的招投标采购信息平台
  • 插入点(position) 和对齐点(AlignmentPoint)详解——CAD c#二次开发
  • 59、定制化原理-SpringBoot定制化组件的几种方式
  • STM32 vs RT1176:正交编码器实现原理与工程实践全解析
  • AI-调查研究-06-“冷水澡”对生理健康的影响与机制【下篇】
  • LangChain自动化工作流实战教程:从任务编排到智能决策
  • FOC无刷电机控制:ABZ与SPI信号选择
  • 【0.1 漫画计算机组成原理】
  • Vue3 + TypeScript + Element Plus 使用【设置表格列宽,组合式函数 hook】在原有页面实现表格列宽设置本地持久化实例总结
  • MySQL(75)如何进行增量备份和恢复?