当前位置:网站首页>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)
总结
字典树板子
可以寻找若干前缀中的最短符合前缀
边栏推荐
- Navigation — 这么好用的导航框架你确定不来看看?
- VSCode 配置使用 PyLint 语法检查器
- 股票开户首选,炒股交易开户佣金最低网上开户安全吗
- 搜索引擎接口
- 最长上升子序列模型 AcWing 482. 合唱队形
- Is the compass stock software reliable? Is it safe to trade stocks?
- Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
- IP and long integer interchange
- 【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(二)
- requires php ~7.1 -> your PHP version (7.0.18) does not satisfy that requirement
猜你喜欢

Multi merchant mall system function disassembly lecture 01 - Product Architecture

OAuth 2.0 + JWT protect API security

手把手教会:XML建模

小米的芯片自研之路

数据流图,数据字典

PERT图(工程网络图)

How to check the ram and ROM usage of MCU through Keil

Introduction to sakt method

今日睡眠质量记录78分

AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
随机推荐
常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码
手把手教会:XML建模
Clickhouse (03) how to install and deploy Clickhouse
Leetcode - Sword finger offer 05 Replace spaces
Laravel form builder uses
The longest ascending subsequence model acwing 1014 Mountaineering
【网络安全】sql注入语法汇总
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
oracle 非自动提交解决
Wired network IP address of VMware shared host
Interface automation test - solution of data dependency between interfaces
Excusez - moi, l'exécution a été réussie lors de l'utilisation des données de puits SQL Flink à Kafka, mais il n'y a pas de nombre dans Kafka
课设之百万数据文档存取
When FC connects to the database, do you have to use a custom domain name to access it outside?
Details of redis core data structure & new features of redis 6
Excuse me, when using Flink SQL sink data to Kafka, the execution is successful, but there is no number in Kafka
PERT图(工程网络图)
3D detection: fast visualization of 3D box and point cloud
Parameter keywords final, flags, internal, mapping keywords internal
C # use TCP protocol to establish connection