面试经典150题——字典树

news/2025/2/11 17:59:26/

文章目录

  • 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/news/1571214.html

相关文章

C++ labmbd表达式

文章目录 C++ Lambda 表达式详解1. Lambda 表达式的组成部分:2. Lambda 语法示例(1) 最简单的 Lambda(2) 带参数的 Lambda(3) 指定返回类型的 Lambda3. 捕获外部变量(1) 值捕获(复制)(2) 引用捕获(3) 捕获所有变量4. Lambda 在 STL 中的应用5. Lambda 作为 `std::function`6…

web前端录制canvas视频和video的声音,并合并成一个文件进行下载

一、captureStream ‌captureStream‌是一个Web API方法&#xff0c;用于捕获指定元素的媒体流。该方法通常用于从<video>、<audio>或<canvas>元素中捕获实时视频流或音频流&#xff0c;以便进行进一步的处理&#xff0c;如直播、录制或分析‌。 captureStr…

Elasticsearch 7 集群搭建问题排查:常见故障解决方案与优化技巧

引言 Elasticsearch 作为一种强大的分布式搜索引擎,已被广泛应用于各种场景,特别是在日志聚合、数据分析等领域中。然而,在实际部署中,尤其是集群搭建阶段,许多用户都会遇到配置问题,导致集群无法成功建立。在本文中,我们将通过一个实际的案例,详细分析和排查 Elastic…

collabora online+nextcloud+mariadb在线文档协助

1、环境 龙蜥os 8.9 docker 2、安装docker dnf -y install dnf-plugins-core dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo sed -i shttps://download.docker.comhttps://mirrors.tuna.tsinghua.edu.cn/docker-ce /etc/yum.repos.…

国产化人工智能“产学 研用”一体化创新模式的智慧快消开源了

智慧快消视频监控平台是一款功能强大且简单易用的实时算法视频监控系统。它的愿景是最底层打通各大芯片厂商相互间的壁垒&#xff0c;省去繁琐重复的适配流程&#xff0c;实现芯片、算法、应用的全流程组合&#xff0c;从而大大减少企业级应用约95%的开发成本。国产化人工智能“…

FFmpeg(一) 简介

FFmpeg 官网 FFmpeg 下载 ffmpeg-release-essentials.7z ffmpeg-release-full-shared.7z FFmpeg既是一款音视频编解码工具&#xff0c;同时也是一组音社频编解码开发套件 FFmpeg包含 多种音视频编码多种协议的流媒体多种色彩格式转换多种采样率转换多种码率转换多种丰富的…

deepseek API 调用-python

【1】创建 API keys 【2】安装openai SDK pip3 install openai 【3】代码&#xff1a; https://download.csdn.net/download/notfindjob/90343352

c语言:取绝对值

假设我们有一个 long 类型的变量 l&#xff0c;我们希望恢复其绝对值。以下是两种方法的对比&#xff1a; 方法1&#xff1a;使用条件语句 这个很好理解&#xff0c;负数时取负运算 &#xff0c;用于数值的符号反转。 long abs_value(long l) {if (l < 0) {return -l;} e…