当前位置:网站首页>648. Word replacement: the classic application of dictionary tree
648. Word replacement: the classic application of dictionary tree
2022-07-07 13:46:00 【Gong Shui Sanye's Diary of writing questions】
Title Description
This is a LeetCode Upper 648. Word substitution , The difficulty is secondary .
Tag : 「 Dictionary tree 」
In English , We have one called Root (root) The concept of , You can add other words after the root to form another longer word —— We call it Inheritance words (successor). for example , Root an, Follow the word other( other ), Can form new words another( the other one ).
Now? , Given a dictionary consisting of many roots dictionary And a sentence formed by separating words with spaces sentence. You need to replace all the inherited words in the sentence with roots . If an inherited word has many roots that can form it , Replace it with the shortest root .
You need to output the replaced sentences .
Example 1:
Input :dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
Output :"the cat was rat by the bat"
Example 2:
Input :dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output :"a a b c"
Tips :
dictionary[i]It's only made up of lowercase letters .sentenceOnly lowercase letters and spaces .sentenceThe total number of words in the range Inside .sentenceThe length of each word in the range Inside .sentenceWords in are separated by a space .sentenceNo leading or trailing spaces .
Basic analysis
This is a way Trie The template question of , I don't know yet Trie Students can look at the front :【 Design data structure 】 Realization Trie ( Prefix tree )
In front of It explains Trie Structure and principle of , And provides two implementations Trie The way .
Back to the subject , For convenience , We make ds by dictionary, Make s by sentence.
Two dimensional array
A more customary practice , It's using 「 Two dimensional array 」 To achieve Trie, coordination static Optimize , Can effectively control new The number of times , The time consumption is relatively stable .
Consider two Trie Basic operation :
addoperation : Variable input parameter strings, Map each character in the string to , At the same time, in order to facilitate the query of a string ( Not just a prefix ) Have you ever depositedTriein , Use an extra Boolean arrayisEndRecord whether a position is the end of a word .queryoperation :
As for the size estimation of two-dimensional array , It can be opened directly , among To insert into Trie The total number of characters in , Is the corresponding character set size . stay No, MLE At risk , You can drive so much directly ; And when more ( exceed , even to the extent that when ), You can properly Medium Reduce , Make the total space in about , Because in fact, more than one character will be stored in some lines of the two-dimensional array , In fact, we don't need so many lines .
Code ( Don't use static Optimize , It takes ten times longer ):
class Solution {
static int N = 100000, M = 26;
static int[][] tr = new int[N][M];
static boolean[] isEnd = new boolean[N * M];
static int idx;
void add(String s) {
int p = 0;
for (int i = 0; i < s.length(); i++) {
int u = s.charAt(i) - 'a';
if (tr[p][u] == 0) tr[p][u] = ++idx;
p = tr[p][u];
}
isEnd[p] = true;
}
String query(String s) {
for (int i = 0, p = 0; i < s.length(); i++) {
int u = s.charAt(i) - 'a';
if (tr[p][u] == 0) break;
if (isEnd[tr[p][u]]) return s.substring(0, i + 1);
p = tr[p][u];
}
return s;
}
public String replaceWords(List<String> ds, String s) {
for (int i = 0; i <= idx; i++) {
Arrays.fill(tr[i], 0);
isEnd[i] = false;
}
for (String d : ds) add(d);
StringBuilder sb = new StringBuilder();
for (String str : s.split(" ")) sb.append(query(str)).append(" ");
return sb.substring(0, sb.length() - 1);
}
}
Time complexity : Make , by slength , The complexity isSpatial complexity : , among Is the character set size
TrieNode
Another can effectively avoid 「 Estimate the size of the array 」 How to operate , It's using TrieNode The way to achieve Trie: Trigger every time you use a new grid new operation .
As for why TrieNode The way , I will still use 「 Two dimensional array 」 Priority approach , stay You know A classmate asked me a similar question , But the original problem is 「 Why is there a dynamic open point segment tree , direct build Out The practice of space still makes sense 」, This corresponds to the use of 「 Two dimensional array 」 still 「TrieNode」 It's the same thing :
Unless some languages start , In the way of virtual machine , And allocate enough memory in advance , Otherwise, all of them new Operations need to be reflected in os On , And in the linux When allocating, you need to traverse the red black tree , So even the total space is the same , disposable new It's smaller than many times new Save time , At the same time, it is centralized new It is also more dispersive new Operate faster , That's why we don't use mindlessly TrieNode Why .
Code :
class Solution {
class Node {
boolean isEnd;
Node[] tns = new Node[26];
}
Node root = new Node();
void add(String s) {
Node p = root;
for (int i = 0; i < s.length(); i++) {
int u = s.charAt(i) - 'a';
if (p.tns[u] == null) p.tns[u] = new Node();
p = p.tns[u];
}
p.isEnd = true;
}
String query(String s) {
Node p = root;
for (int i = 0; i < s.length(); i++) {
int u = s.charAt(i) - 'a';
if (p.tns[u] == null) break;
if (p.tns[u].isEnd) return s.substring(0, i + 1);
p = p.tns[u];
}
return s;
}
public String replaceWords(List<String> ds, String s) {
for (String str : ds) add(str);
StringBuilder sb = new StringBuilder();
for (String str : s.split(" ")) sb.append(query(str)).append(" ");
return sb.substring(0, sb.length() - 1);
}
}
Time complexity : Make , by slength , The complexity isSpatial complexity : , among Is the character set size
snacks
Today, I add an extra meal question that is more suitable for the written examination interview : combination DFS Of Trie Application questions
Last
This is us. 「 Brush through LeetCode」 The first of the series No.648 piece , The series begins with 2021/01/01, As of the start date LeetCode I have in common 1916 questions , Part of it is a locked question , We will finish all the questions without lock first .
In this series , In addition to explaining the idea of solving problems , And give the most concise code possible . If the general solution is involved, there will be corresponding code templates .
In order to facilitate the students to debug and submit code on the computer , I've built a warehouse :https://github.com/SharingSource/LogicStack-LeetCode .
In the warehouse address , You can see the links to the series 、 The corresponding code of the series 、LeetCode Links to the original problem and other preferred solutions .
More, more, more popular 「 written examination / interview 」 Relevant information can be found in the beautifully arranged Gather new bases
边栏推荐
- 得物客服热线的演进之路
- Getting started with MySQL
- 566. 重塑矩阵
- Thread pool reject policy best practices
- clion mingw64中文乱码
- Japanese government and enterprise employees got drunk and lost 460000 information USB flash drives. They publicly apologized and disclosed password rules
- 【等保】云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
- 实现IP地址归属地显示功能、号码归属地查询
- Vscade editor esp32 header file wavy line does not jump completely solved
- User management summary of mongodb
猜你喜欢
![Supply chain supply and demand estimation - [time series]](/img/2c/82d118cfbcef4498998298dd3844b1.png)
Supply chain supply and demand estimation - [time series]

How far can it go to adopt a cow by selling the concept to the market?

Ways to improve the performance of raspberry pie

Sliding rail stepping motor commissioning (national ocean vehicle competition) (STM32 master control)

2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array

Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf

LED light of single chip microcomputer learning notes

High end for 8 years, how is Yadi now?

我那“不好惹”的00后下属:不差钱,怼领导,抵制加班

QQ medicine, Tencent ticket
随机推荐
RealBasicVSR测试图片、视频
Ways to improve the performance of raspberry pie
[learning notes] agc010
干货|总结那些漏洞工具的联动使用
Clion mingw64 Chinese garbled code
Getting started with MySQL
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
Vscade editor esp32 header file wavy line does not jump completely solved
OSI seven layer model
Introduction and basic use of stored procedures
云计算安全扩展要求关注的安全目标和实现方式区分原则有哪些?
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours
Navicat run SQL file import data incomplete or import failed
1. Deep copy 2. Call apply bind 3. For of in differences
为租客提供帮助
Thread pool reject policy best practices
Signal strength (RSSI) knowledge sorting
Esp32 ① compilation environment
【日常训练--腾讯精选50】231. 2 的幂
OSI 七层模型