LeetCode 127 Word Ladder
来源:互联网 发布:saber软件正版价格 编辑:程序博客网 时间:2024/05/17 02:04
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.
Runtime: 21 ms beats 99.30% of java submissions.
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {Set<String> start = new HashSet<>(), end = new HashSet<>();start.add(beginWord);end.add(endWord);return solve(start, end, wordList, 1);}public int solve(Set<String> start, Set<String> end, Set<String> wordList, int level) {if (start.isEmpty()) return 0;if (start.size() > end.size()) return solve(end, start, wordList, level);//cut the loopwordList.removeAll(start);wordList.removeAll(end);Set<String> set = new HashSet<>();for (String s : start) {char[] chars = s.toCharArray();for (int i = 0; i < s.length(); i++) {for (char ch = 'a'; ch <= 'z'; ch++) {char temp = chars[i];chars[i] = ch;String word = new String(chars);if (end.contains(word)) return level + 1;//found the word in other end(set)if (wordList.contains(word)) set.add(word);// if not, add to the next levelchars[i] = temp;}}}return solve(set, end, wordList, level + 1);}https://discuss.leetcode.com/topic/40797/share-my-19ms-java-code
0 0
- leetcode 127 Word Ladder
- [leetcode 127]Word Ladder
- LeetCode(127) Word Ladder
- LeetCode 127 Word Ladder
- LeetCode(127) Word Ladder
- leetcode 127: Word Ladder
- 127 Word Ladder [Leetcode]
- LeetCode 127 Word Ladder
- Leetcode 127 Word Ladder
- leetcode 127 Word Ladder
- LeetCode 127 Word Ladder
- LeetCode 127 Word Ladder
- Leetcode 127 Word Ladder I
- LeetCode: Word Ladder II [127]
- [leetcode]127 Word Ladder BFS
- [leetcode-127]Word Ladder(java)
- [Leetcode][python]Word Ladder/Word Ladder II
- leetcode 127 —— Word Ladder
- 二叉树整理(四)
- 永远不要对一个外行聊你的专业
- 大数阶乘问题
- Eclipse中.setting目录下文件介绍
- c语言简单文件加密
- LeetCode 127 Word Ladder
- 【C++竞赛 A】xxx的项链
- cocoapods升级1.1.1
- C/C++ 离高考还有几天
- java压缩
- 什么是闭包
- 对自己无语的_数据结构-二叉树
- java与mysql的简单连接与编译
- VxWorks学习之路之VxWorks简介