面试经典150题——字典树

server/2025/2/12 18:39:06/

文章目录

  • 1、实现 Trie (前缀树)
    • 1.1 题目链接
    • 1.2 题目描述
    • 1.3 解题代码
    • 1.4 解题思路
  • 2、添加与搜索单词 - 数据结构设计
    • 2.1 题目链接
    • 2.2 题目描述
    • 2.3 解题代码
    • 2.4 解题思路
  • 3、单词搜索 II
    • 3.1 题目链接
    • 3.2 题目描述
    • 3.3 解题代码
    • 3.4 解题思路


对于字典树而言,之前做过类似的教程,详情可以看走入字典树一。

1、实现 Trie (前缀树)

1.1 题目链接

点击跳转到题目位置

1.2 题目描述

Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补全和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。

提示:

  • 1 <= word.length, prefix.length <= 2000
  • word 和 prefix 仅由小写英文字母组成
  • insert、search 和 startsWith 调用次数 总计 不超过 3 * 104

1.3 解题代码


class TrieNode{TrieNode[] next;boolean end;TrieNode(){next = new TrieNode[26];end = false;}
}class Trie {TrieNode root;public Trie() {root = new TrieNode();}public void insert(String word) {TrieNode now = root;for(int i = 0; i < word.length(); ++i){int child = word.charAt(i) - 'a';if(now.next[child] == null){now.next[child] = new TrieNode();}now = now.next[child];}now.end = true;}public boolean search(String word) {TrieNode now = root;for(int i = 0; i < word.length(); ++i){int child = word.charAt(i) - 'a';if(now.next[child] == null){return false;}now = now.next[child]; }return now.end;}public boolean startsWith(String prefix) {TrieNode now = root;for(int i = 0; i < prefix.length(); ++i){int child = prefix.charAt(i) - 'a';if(now.next[child] == null){return false;}now = now.next[child]; }return true;}
}/*** Your Trie object will be instantiated and called as such:* Trie obj = new Trie();* obj.insert(word);* boolean param_2 = obj.search(word);* boolean param_3 = obj.startsWith(prefix);*/

1.4 解题思路

  1. 字典树经典题型,套用模板即可。

2、添加与搜索单词 - 数据结构设计

2.1 题目链接

点击跳转到题目位置

2.2 题目描述

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

实现词典类 WordDictionary :

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

提示:

  • 1 <= word.length <= 25
  • addWord 中的 word 由小写英文字母组成
  • search 中的 word 由 ‘.’ 或小写英文字母组成
  • 最多调用 104 次 addWord 和 search

2.3 解题代码

class TrieNode{TrieNode[] next;boolean end;TrieNode(){next = new TrieNode[26];end = false;}
}class WordDictionary {TrieNode root;public WordDictionary() {root = new TrieNode();}public void addWord(String word) {TrieNode now = root;for(int i = 0; i < word.length(); ++i){int child = word.charAt(i) - 'a';if(now.next[child] == null){now.next[child] = new TrieNode();}now = now.next[child];    }now.end = true;}public boolean search(String word) {Queue<TrieNode> q = new LinkedList<>();q.offer(root);for(int i = 0; i < word.length(); ++i){int len = q.size();for(int j = 0; j < len; ++j){ TrieNode x = q.peek();q.poll();if(word.charAt(i) == '.'){for(int k = 0; k < 26; ++k){if(x.next[k] != null){q.offer(x.next[k]);}}} else{int child = word.charAt(i) - 'a';if(x.next[child] != null){q.offer(x.next[child]);}} }if(q.size() == 0){return false;}}while(!q.isEmpty()){TrieNode x = q.peek();if(x.end == true){return true;}q.poll();}return false;}
}/*** Your WordDictionary object will be instantiated and called as such:* WordDictionary obj = new WordDictionary();* obj.addWord(word);* boolean param_2 = obj.search(word);*/

2.4 解题思路

  1. 套用字典树模板。
  2. 对于搜索,因为癞子的存在,所以需要使用广度优先搜索

3、单词搜索 II

3.1 题目链接

点击跳转到题目位置

3.2 题目描述

给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words, 返回所有二维网格上的单词 。

单词必须按照字母顺序,通过 相邻的单元格 内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。

3.3 解题代码

class Solution {int[][] dir = {{-1, 0},{1, 0},{0, 1},{0, -1},};Trie trie = new Trie();List<String> res = new ArrayList<>();public void dfs(TrieNode root, int x, int y, int m, int n, char[][] board, int vis[][], StringBuffer sb){        if(root.end == true){String str = sb.toString();res.add(str);root.end = false;}for(int i = 0; i < 4; ++i){int tx = x + dir[i][0];int ty = y + dir[i][1];if(tx < 0 || tx >= m || ty < 0 || ty >= n || vis[tx][ty] == 1){continue;}if(root.next[board[tx][ty] - 'a'] != null){vis[tx][ty] = 1;sb.append(board[tx][ty]);dfs(root.next[board[tx][ty] - 'a'], tx, ty, m, n, board, vis, sb);sb.deleteCharAt(sb.length() - 1);vis[tx][ty] = 0;}}} public List<String> findWords(char[][] board, String[] words) {int m = board.length;int n = board[0].length;int[][] vis = new int[m][n];for(int i = 0; i < words.length; ++i){trie.insert(words[i]);}StringBuffer sb = new StringBuffer();Queue<Character> q = new LinkedList<>();for(int i = 0; i < m; ++i){for(int j = 0; j < n; ++j){if(trie.root.next[board[i][j] - 'a'] != null){vis[i][j] = 1;sb.append(board[i][j]);dfs(trie.root.next[board[i][j] - 'a'], i, j, m, n, board, vis, sb);sb.deleteCharAt(sb.length() - 1);vis[i][j] = 0;}             }}return res;}
}class TrieNode{TrieNode[] next;boolean end;TrieNode(){next = new TrieNode[26];end = false;}
}class Trie {TrieNode root;public Trie() {root = new TrieNode();}public void insert(String word) {TrieNode now = root;for(int i = 0; i < word.length(); ++i){int child = word.charAt(i) - 'a';if(now.next[child] == null){now.next[child] = new TrieNode();}now = now.next[child];}now.end = true;}public boolean search(String word) {TrieNode now = root;for(int i = 0; i < word.length(); ++i){int child = word.charAt(i) - 'a';if(now.next[child] == null){return false;}now = now.next[child]; }return now.end;}public boolean startsWith(String prefix) {TrieNode now = root;for(int i = 0; i < prefix.length(); ++i){int child = prefix.charAt(i) - 'a';if(now.next[child] == null){return false;}now = now.next[child]; }return true;}
}

3.4 解题思路

1, 字典树+回溯思路
2, 如果字典树中存在该字符串,将其放入数组当中,然后将字典树中的该字符串去掉。


http://www.ppmy.cn/server/167120.html

相关文章

判断192.168.1.0/24网络中,当前在线的ip有哪些

需求&#xff1a;判断192.168.1.0/24网络中&#xff0c;当前在线的ip有哪些&#xff0c;并编写脚本打印出来。 [rootopenEuler ~]# cat 1.sh #!/bin/bash for ip in $(seq 1 254); do ping -c 1 -W 1 "192.168.1.$ip" > /dev/null 2>&1 if [ $? …

DeepSeek-Coder系列模型:智能编程助手的未来

文章目录 一、模型架构与核心功能1. 模型架构2. 核心功能 二、多语言支持与代码生成1. Python代码生成2. Java代码生成3. C代码生成4. JavaScript代码生成 三、仓库级代码理解1. 代码结构分析2. 上下文理解 四、FIM填充技术1. 函数自动填充2. 代码补全 五、应用场景1. 代码补全…

设计模式-结构型-外观模式

在软件开发中&#xff0c;随着功能的不断迭代&#xff0c;系统会变得越来越复杂&#xff0c;模块之间的依赖关系也会越来越深。这种复杂性会导致代码难以理解、维护和扩展。而外观模式&#xff08;Facade Pattern&#xff09;正是为了解决这一问题而生的。 一、外观模式简介 …

二分算法篇:二分答案法的巧妙应用

二分算法篇&#xff1a;二分答案法的巧妙应用 那么看到二分这两个字想必我们一定非常熟悉&#xff0c;那么在大学期间的c语言的教学中会专门讲解二分查找&#xff0c;那么我们来简单回顾一下二分查找算法&#xff0c;我们知道二分查找是在一个有序的序列中寻找一个数在这个序列…

VS2022中cmath.h头文件功能介绍

在C语言的世界里&#xff0c;数学运算一直是程序开发中不可或缺的一部分。无论是进行简单的数值计算&#xff0c;还是处理复杂的科学工程问题&#xff0c;都需要借助数学函数来实现。在Visual Studio 2022&#xff08;VS2022&#xff09;中&#xff0c;cmath.h&#xff08;在C语…

计算机毕业设计——Springboot点餐平台网站

&#x1f4d8; 博主小档案&#xff1a; 花花&#xff0c;一名来自世界500强的资深程序猿&#xff0c;毕业于国内知名985高校。 &#x1f527; 技术专长&#xff1a; 花花在深度学习任务中展现出卓越的能力&#xff0c;包括但不限于java、python等技术。近年来&#xff0c;花花更…

【编程实践】vscode+pyside6环境部署

1 PySide6简介 PySide6是Qt for Python的官方版本&#xff0c;支持Qt6&#xff0c;提供Python访问Qt框架的接口。优点包括官方支持、LGPL许可&#xff0c;便于商业应用&#xff0c;与Qt6同步更新&#xff0c;支持最新特性。缺点是相比PyQt5&#xff0c;社区资源较少。未来发展…

React 高级教程

使用 React 高级组件(HOC)实现的完整项目示例,包含权限控制、数据加载状态处理、性能优化等常见高级功能。创建一个简单的博客系统: // 项目结构: src/ |-- components/ | |-- ArticleList.jsx | |-- Article.jsx | |-- Header.jsx | |-- LoginForm.jsx | |-- U…