当前位置:网站首页>leetcode:648. Word replacement [dictionary tree board + find the shortest matching prefix among several prefixes]
leetcode:648. Word replacement [dictionary tree board + find the shortest matching prefix among several prefixes]
2022-07-07 14:39:00 【White speed Dragon King's review】

analysis
To a Trie Record dictionary tree
Then traverse word by word , use cur Go to the current layer
If you traverse to a c, Not in the cur in , Set up cur[c] It's empty , cur = cur[c]
At the end, let's say # It means the ending
Then traverse sentence Every word in , If you traverse to # Description matches a prefix , Prefix replacement
If you find out that c be not in cur in , It means that there is no match , direct break
ac code
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
# Dictionary tree board
trie = {
}
for word in dictionary:
cur = trie
for c in word:
# New branch
if c not in cur:
cur[c] = {
}
cur = cur[c]
# End mark
cur['#'] = {
}
words = sentence.split()
for i in range(len(words)):
# stay trie Find the shortest prefix
cur = trie
for j, c in enumerate(words[i]):
# Match to the first prefix
if '#' in cur:
words[i] = words[i][:j]
break
# Matching failure
if c not in cur:
break
# Continue matching
cur = cur[c]
#print(words)
return ' '.join(words)
summary
Dictionary tree board
You can find the shortest matching prefix among several prefixes
边栏推荐
- Navigation — 这么好用的导航框架你确定不来看看?
- EfficientNet模型的完整细节
- 一个程序员的水平能差到什么程度?尼玛,都是人才呀...
- ES日志报错赏析-trying to create too many buckets
- 大厂做开源的五大痛点
- Differences between cookies and sessions
- The longest ascending subsequence model acwing 1014 Mountaineering
- Leetcode——剑指 Offer 05. 替换空格
- 低代码平台中的数据连接方式(下)
- [Reading stereo matching papers] [III] ints
猜你喜欢

2022PAGC 金帆奖 | 融云荣膺「年度杰出产品技术服务商」

Data Lake (IX): Iceberg features and data types

Base64 encoding

Because the employee set the password to "123456", amd stolen 450gb data?

MicTR01 Tester 振弦采集模块开发套件使用说明

LeetCode 648. 单词替换

【历史上的今天】7 月 7 日:C# 发布;Chrome OS 问世;《仙剑奇侠传》发行

JS get the current time, month, day, year, and the uniapp location applet opens the map to select the location

UML state diagram

STM32CubeMX,68套组件,遵循10条开源协议
随机推荐
一款你不容错过的Laravel后台管理扩展包 —— Voyager
低代码平台中的数据连接方式(下)
电脑Win7系统桌面图标太大怎么调小
Analysis of arouter
Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
在软件工程领域,搞科研的这十年!
设备故障预测机床故障提前预警机械设备振动监测机床故障预警CNC震动无线监控设备异常提前预警
Substance Painter筆記:多顯示器且多分辨率顯示器時的設置
《微信小程序-进阶篇》组件封装-Icon组件的实现(一)
Mlgo: Google AI releases industrial compiler optimized machine learning framework
Selenium Library
课设之百万数据文档存取
Webrtc audio anti weak network technology (Part 1)
用例图
Similarities and differences between switches and routers
C 6.0 language specification approved
属性关键字OnDelete,Private,ReadOnly,Required
MRS离线数据分析:通过Flink作业处理OBS数据
GAN发明者Ian Goodfellow正式加入DeepMind,任Research Scientist
In the field of software engineering, we have been doing scientific research for ten years!