【leetcode】Word Ladder
Word Ladder
Total Accepted: 24823 Total Submissions: 135014My SubmissionsGiven two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
Hide Tags
Breadth-first Search利用广度优先搜索,找到元素的深度即可
寻找相差一个字符的字符串时,考虑采用替换字符的方式寻找,遍历dict在dict很长时,会耗时
1 int ladderLength(string start, string end, unordered_set<string> &dict) { 2 int n=start.size(); 3 if(n<1||n!=end.size()) 4 { 5 return 0; 6 } 7 if(start==end) 8 { 9 return 1; 10 } 11 12 int level=2; 13 queue<string> q; 14 q.push(start); 15 //count用来记录每一个深度的元素的个数 16 int count=1; 17 while(1) 18 { 19 start=q.front(); 20 q.pop(); 21 count--; 22 for(int i=0;i<start.length();i++) 23 { 24 string ori=start; 25 //每次修改一个字符,看是否在字典中能找到 26 for(char ch='a';ch<='z';ch++) 27 { 28 if(start[i]==ch)continue; 29 30 start[i]=ch; 31 if(start==end) return level; 32 //如果能找到,则用queue记录下下一层深度的元素 33 if(dict.find(start)!=dict.end()) 34 { 35 dict.erase(start); 36 q.push(start); 37 } 38 start=ori; 39 } 40 } 41 42 //没有下一层深度了,或者dict已经为空 43 if(q.empty()||dict.empty()) 44 { 45 break; 46 } 47 48 //count为0,说明该level的元素已经被遍历完了 49 if(count==0) 50 { 51 level++; 52 count=q.size(); 53 } 54 } 55 return 0; 56 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现