当前位置:网站首页>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)
总结
字典树板子
可以寻找若干前缀中的最短符合前缀
边栏推荐
- Similarities and differences between switches and routers
- C # use TCP protocol to establish connection
- 一个程序员的水平能差到什么程度?尼玛,都是人才呀...
- NLLB-200:Meta开源新模型,可互译200种语言
- Reading and understanding of eventbus source code
- MLGO:Google AI发布工业级编译器优化机器学习框架
- 最长上升子序列模型 AcWing 482. 合唱队形
- Leetcode - Sword finger offer 05 Replace spaces
- Horizontal of libsgm_ path_ Interpretation of aggregation program
- 2022PAGC 金帆奖 | 融云荣膺「年度杰出产品技术服务商」
猜你喜欢

LeetCode 648. Word replacement
![GVIM [III] [u vimrc configuration]](/img/82/38355d7914e5fe490546347e57e35d.png)
GVIM [III] [u vimrc configuration]

一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】

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

Reverse non return to zero code, Manchester code and differential Manchester code of common digital signal coding

docker部署oracle

js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点

低代码平台中的数据连接方式(下)
![Verilog implementation of a simple legv8 processor [4] [explanation of basic knowledge and module design of single cycle implementation]](/img/d3/20674983717d829489149b4d3bfedf.png)
Verilog implementation of a simple legv8 processor [4] [explanation of basic knowledge and module design of single cycle implementation]

最长上升子序列模型 AcWing 1014. 登山
随机推荐
Leetcode——236. The nearest common ancestor of binary tree
AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
First choice for stock account opening, lowest Commission for stock trading account opening, is online account opening safe
[untitled]
Similarities and differences between switches and routers
FCOS3D label assignment
PERT图(工程网络图)
交换机和路由器的异同
内部排序——插入排序
Is the compass stock software reliable? Is it safe to trade stocks?
Mmkv use and principle
Details of redis core data structure & new features of redis 6
請問,在使用flink sql sink數據到kafka的時候出現執行成功,但是kafka裏面沒有數
一文读懂数仓中的pg_stat
How can the PC page call QQ for online chat?
UML 顺序图(时序图)
3D Detection: 3D Box和点云 快速可视化
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
call undefined function openssl_ cipher_ iv_ length
ndk初学习(一)