127. Word Ladder via java
2024-10-20 04:11:48
A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue.
For each node in this BFS tree, we try k times of transformation, k is the length of the word.
We record every word which already has been seen in case of a loop. Thus we need a HashSet.
public class Solution {
// use BFS to solve
// in every level of BFS searching,
// we find the word that replaced by one char and also in the dict without have seen before
// data structure: seen(HashSet), cur(Queue)
// assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
// Write your solution here
HashSet<String> seen = new HashSet<>();
Queue<String> cur = new LinkedList<>();
seen.add(beginWord);
cur.offer(beginWord);
int cnt = 1;
while(cur.size()>0){
cnt++;
int size = cur.size();
for(int i=0; i<size; i++){
String todo = cur.poll();
for(int j=0; j<todo.length(); j++){
List<String> changed= getQualified(todo, j, wordList, seen);
for(String s: changed){
if(String.valueOf(s)==String.valueOf(endWord)){
return cnt;
}else{
cur.offer(s);
seen.add(s);
}
}
}
}
}
return 0;
} private List<String> getQualified(String from, int ignore, List<String> wordList, HashSet<String> seen){
List<String> res = new ArrayList<>();
for(String s: wordList){
int flag = 0;
for(int i=0; i<from.length(); i++){
if(i!=ignore && from.charAt(i)!=s.charAt(i)){
flag=1;
}
}
if(flag==0 && !seen.contains(s)){
res.add(s);
}
}
return res;
}
}
最新文章
- jqueryui 进度条使用
- 关于由CSS2.1所提出的的BFC的理解与样例
- UDP及其组播,接收发送封装
- 《致命接触》:人畜共患传染病的故事,SARS一章非常精彩,四星推荐
- Java 迭代器理解
- Codeforces 435 B Pasha Maximizes【贪心】
- 从UnitedStack OS 1.0 Preview试用申请问卷调查学习OpenStack
- 检测Insert、Capslock、NumLock、ScrollLock状态键的状态
- Java学习笔记——山西煤老板蛋疼的拉车问题
- javascript痛点之一变量作用域
- 一张图告诉你 canvas 中的 miterLimit 代表着什么
- Linux的五种I/O模式
- qt学习教程1.qt开发环境搭建
- python (5分钟实现一个游戏的屏蔽敏感字系统,)
- 基于GitLab的Code Review教程
- django.core.exceptions.AppRegistryNotReady: Apps aren&#39;t loaded yet.
- 进一步聊聊weight initialization
- Spring Boot初识(3)- Spring Boot整合Swagger
- selenium&#160;之百度搜索,结果列表翻页查询
- JavaScript学习总结(二十)——Javascript非构造函数的继承