当前位置:网站首页>leetcode:648. 单词替换【字典树板子 + 寻找若干前缀中的最短符合前缀】
leetcode:648. 单词替换【字典树板子 + 寻找若干前缀中的最短符合前缀】
2022-07-07 12:35:00 【白速龙王的回眸】

分析
来个Trie记录字典树
然后一个个单词遍历,用cur去到当前层
如果遍历到某个c,没有在cur中,设置cur[c]为空, cur = cur[c]
结尾的时候来个#表示结束符
然后遍历sentence中的每个单词,如果遍历到#说明匹配到某个前缀了,进行前缀替换
如果发现当前c不在cur中,说明匹配不下去了,直接break
ac code
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
# 字典树板子
trie = {
}
for word in dictionary:
cur = trie
for c in word:
# 新增分支
if c not in cur:
cur[c] = {
}
cur = cur[c]
# 结束标志
cur['#'] = {
}
words = sentence.split()
for i in range(len(words)):
# 在trie寻找最短前缀
cur = trie
for j, c in enumerate(words[i]):
# 匹配到第一个前缀
if '#' in cur:
words[i] = words[i][:j]
break
# 匹配失败
if c not in cur:
break
# 继续匹配
cur = cur[c]
#print(words)
return ' '.join(words)
总结
字典树板子
可以寻找若干前缀中的最短符合前缀
边栏推荐
- OAuth 2.0 + JWT protect API security
- 小程序目录结构
- Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding
- Vscode configuration uses pylint syntax checker
- Equipment failure prediction machine failure early warning mechanical equipment vibration monitoring machine failure early warning CNC vibration wireless monitoring equipment abnormal early warning
- Take you to master the three-tier architecture (recommended Collection)
- LeetCode 648. 单词替换
- 常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
- Multi merchant mall system function disassembly lecture 01 - Product Architecture
- 最长上升子序列模型 AcWing 482. 合唱队形
猜你喜欢

Flask session forged hctf admin

The longest ascending subsequence model acwing 1014 Mountaineering

设备故障预测机床故障提前预警机械设备振动监测机床故障预警CNC震动无线监控设备异常提前预警

低代码平台中的数据连接方式(下)

最长上升子序列模型 AcWing 482. 合唱队形

Selenium Library

数据流图,数据字典

Data flow diagram, data dictionary

Pert diagram (engineering network diagram)

一个程序员的水平能差到什么程度?尼玛,都是人才呀...
随机推荐
杭电oj2092 整数解
OAuth 2.0 + JWT protect API security
Oracle non automatic submission solution
UML state diagram
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
Codes de non - retour à zéro inversés, codes Manchester et codes Manchester différentiels couramment utilisés pour le codage des signaux numériques
Leetcode——236. The nearest common ancestor of binary tree
Selenium库
Beginner XML
MLGO:Google AI发布工业级编译器优化机器学习框架
一文读懂数仓中的pg_stat
Is the compass stock software reliable? Is it safe to trade stocks?
wpf dataGrid 实现单行某个数据变化 ui 界面随之响应
AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
Data flow diagram, data dictionary
IP and long integer interchange
请问,如图,pyhon云函数提示使用了 pymysql模块,这个是怎么回事?
Huawei image address
IP address home location query
WPF DataGrid realizes the UI interface to respond to a data change in a single line