[Leetcode] Word Ladder
来源:互联网 发布:golang cobra 编辑:程序博客网 时间:2024/06/05 09:03
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["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.
BFS。一开始一直报Timeout,原因是原代码遍历了wordList,然后检查word和现有的word是否diff <= 1,当wordList巨大时开销很大。现在将word每个位置上的char都从a到z的代入,虽然依旧开销很大,但是当wordList很大时反而更有效率。
public class Solution { public int ladderLength(String beginWord, String endWord, Set<String> wordList) { if(beginWord == null || endWord == null || wordList == null || beginWord.equals(endWord)) return 0; int dist = 0; currentLevel.add(beginWord); while(!currentLevel.isEmpty()){ dist++; while(!currentLevel.isEmpty()){ String curWord = currentLevel.remove(); if(curWord.equals(endWord)) return dist; for(int i = 0; i < curWord.length(); i++){ char[] wordArray = curWord.toCharArray(); for(char j = 'a'; j <= 'z'; j++){ wordArray[i] = j; String wordString = new String(wordArray); if(wordList.contains(wordString)){ nextLevel.add(wordString); wordList.remove(wordString); } } } } Queue<String> tmp = nextLevel; nextLevel = currentLevel; currentLevel = tmp; } return 0; } private Queue<String> currentLevel = new ArrayDeque<>(); private Queue<String> nextLevel = new ArrayDeque<>();}
0 0
- [Leetcode][python]Word Ladder/Word Ladder II
- [Leetcode] Word Ladder
- LeetCode: Word Ladder
- leetcode 84: Word Ladder
- [leetcode] word ladder
- 【leetcode】Word Ladder
- 【leetcode】Word Ladder II
- LeetCode - Word Ladder
- LeetCode之Word Ladder
- [LeetCode]Word Ladder
- [LeetCode]Word Ladder II
- [Leetcode]Word Ladder
- [leetcode]Word Ladder
- [leetcode] Word Ladder
- [leetcode] Word Ladder II
- LeetCode-Word Ladder
- LeetCode- Word Ladder
- LeetCode - Word Ladder II
- 顺序表的应用
- 第四周 项目3 单链表的应用
- 第六周项目3—括号的匹配
- Linux下TCP客户端和服务器代码编写
- 第八周 串 项目2 -- 建立链串的算法库
- [Leetcode] Word Ladder
- cookies编程
- 第4周项目6 多项式求和
- iOS-归档模型创建和工具类的封装
- iOS讲解迷惑之键盘弹出遮挡输入框的问题
- 第三周项目4—顺序表的应用(2)
- 第六周项目4-数制转换
- servlet容器和web容器
- 第四周项目 猴子选大王