211. Add and Search Word - Data structure design
package LeetCode_211 /** * 211. Add and Search Word - Data structure design * https://leetcode.com/problems/add-and-search-word-data-structure-design/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. 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. * */ class Trie { var end = false var children = arrayOfNulls<Trie>(26) } class WordDictionary() { /* * solution: Trie Tree, * */ var root: Trie? = null /** Initialize your data structure here. */ init { root = Trie() } /** Adds a word into the data structure. */ fun addWord(word: String) { var node = root //while (k < word.length) { for (ch in word) { val pos = ch - 'a' if (node?.children!![pos] == null) { node.children!![pos] = Trie() } node = node.children!![pos] } node?.end = true } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ fun search(word: String): Boolean { return dfs(word, 0, root) } private fun dfs(word: String, pos: Int, root: Trie?): Boolean { if (root == null) { return false } if (pos == word.length) { return root.end } val ch = word[pos] println("ch:$ch") if (ch == '.') { //if meet '.', need search all children for (child in root.children!!) { if (child != null && dfs(word, pos + 1, child)) { return true } } } else { return dfs(word, pos + 1, root.children!![ch - 'a']) } return false } } /** * Your WordDictionary object will be instantiated and called as such: * var obj = WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)