[LeetCode#127]Word Ladder
---恢复内容开始---
The problem:
Given 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.
My analysis:
This problem's solution is very elegant and tricky! It represents a new kind of problem that could be solved by using abstract graph. The key idea: use the graph to search. But it differs a lot from the previous problem, which has a obvious link or neighbor list of a node. We need to extract this information from a very tricky way. The abstract graph: 1. represent each String in the dictionary as a node in the graph. 2. iff two nodes differ in only one character, there is a edge between those two nodes in the graph.The shortest problem in the grpah:(unweighted graph) The breadth first search could layered the nodes in the graph. The path from source node to another node in the breadth first traversal is the shortest path from source node to the node. The distance is the layer the node in. It seems that there is no linkage domain, how could we traversal? Since we have no link to follow, how about we try all possible pathes according to the requirement! The requirement: Only one letter can be changed at a time. It is not hard to simulate. for (int i = 0; i < cur.length(); i++) {char[] cur_array = cur.toCharArray();for (char c = 'a'; c <= 'z'; c++) {cur_array[i] = c;String temp = new String(cur_array);... } However, the while loop could result in all possbile branches(which only differ a character with the current node). We could only search along the edge that existed in the graph, we need to rule out some unreasonable branches. if (dict.contains(temp) && !visited.contains(temp)) {queue.offer(temp);visited.add(temp);next_num++; }What a beautful way!!!(fake traversal and rule out!)Note: the above rountine is for continue search, which means we have not reach out the "end(target)" String. However, if we reach the target, we could directly return the distance, cause the target need not to be in the dict. for (int i = 0; i < cur.length(); i++) {char[] cur_array = cur.toCharArray();for (char c = 'a'; c <= 'z'; c++) {cur_array[i] = c;String temp = new String(cur_array); if (temp.equals(end))return level + 1;...} }The time complexity analysis: while (!queue.isEmpty()) {...for (int i = 0; i < cur.length(); i++) {...for (char c = 'a'; c <= 'z'; c++) {...if (dict.contains(temp) && !visited.contains(temp)) {queue.offer(temp);visited.add(temp);next_num++;}}} } The time complexity for the big for loop: Length * 26 Since we use "dict.contains(temp)" to restrict searching domain. we enter the for loop at most. dict.size() times. thus the total complexity is size(dict) * length * 26Note: Be very careful with the function of "!visited.contains(temp)". Unlike Binary, there could be circle in the graph, thus we must use visted set to record all nodes we have visited. Otherwise it would result in infinite loop. Cause we keep on(there might be iterleaves) enqueuing and dequeing it.
My solution:
public class Solution {public int ladderLength(String start, String end, Set<String> dict) {if (start == null || end == null || dict == null || start.length() == 0 || end.length() == 0 || dict.size() == 0)return 0;HashSet<String> visited = new HashSet<String> ();Queue<String> queue= new LinkedList<String> ();String cur;queue.offer(start);int cur_num = 1;int next_num = 0;int level = 1;while (!queue.isEmpty()) {cur = queue.poll();cur_num-- ; //only intermdiate string need to be in the dict.for (int i = 0; i < cur.length(); i++) {char[] cur_array = cur.toCharArray();for (char c = 'a'; c <= 'z'; c++) {cur_array[i] = c;String temp = new String(cur_array); //must do it in this way, only change one char a time. if (temp.equals(end))return level + 1;if (dict.contains(temp) && !visited.contains(temp)) {//very imprtant checking condition!!! queue.offer(temp);visited.add(temp);next_num++;}}}if (cur_num == 0) {cur_num = next_num;next_num = 0;level++;}}return 0;} }
---恢复内容结束---
转载于:https://www.cnblogs.com/airwindow/p/4220300.html
[LeetCode#127]Word Ladder相关推荐
- 【重点BFS】LeetCode 127. Word Ladder
LeetCode 127. Word Ladder Solution1:我的超过40%的AC的答案 原先利用BFS做但是内存溢出未能AC:进过修改加上了标记是否访问过的visited数组,可以AC啦~ ...
- LeetCode 127. Word Ladder
原题链接在这里:https://leetcode.com/problems/word-ladder/ 题目: Given two words (beginWord and endWord), and ...
- 【难点+重点BFS】LeetCode 126. Word Ladder II
LeetCode 126. Word Ladder II Solution1: 参考自花花酱:http://zxi.mytechroad.com/blog/searching/leetcode-126 ...
- Leetcode的word ladder问题
127. Word Ladder 题意如下: 给定一个开始字符串和结束字符串以及含有大量字符串的字典,要求通过一定规则,能从开始字符串变换到结束字符串,求其最小变换字符串数目,该规则如下: 1 从开始 ...
- 【LeetCode】127. Word Ladder 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/word-lad ...
- 127. Word Ladder 单词接龙
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度.转换需遵循如下规则: 每次转换只能改变一个字母. 转换过程中的中 ...
- 127. Word Ladder
文章目录 1 题目理解 2 BFS 3 双向BFS 1 题目理解 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度 ...
- 127.Word Ladder
class Solution { public:int ladderLength(string start, string end, unordered_set<string> & ...
- 算法细节系列(20):Word Ladder系列
算法细节系列(20):Word Ladder系列 详细代码可以fork下Github上leetcode项目,不定期更新. 题目摘自leetcode: 1. Leetcode 127: Word Lad ...
最新文章
- aac文件损坏修复软件_Mac不能安装非信任应用的解决方法 MAC软件安装必读 打不开身份不明的开发者?文件已损坏?...
- python类私有函数_python-面向对象-14-私有方法
- 使用RMAN备份控制文件(control file)和系统参数文件(spfile)
- 基于 Kyma 的企业级云原生应用的扩展案例分享
- 初一模拟赛总结(2019.5.25)
- java compareable接口_Java对象比较-Comparable和Comparator接口使用
- [html] H5的Web Storage带来什么好处?
- arduino i2c 如何写16位寄存器_树莓派3B开发Go语言(二)寄存器版本GPIO
- PHP API 框架开发的学习
- SAP License:FI学习笔记
- MS SQL Server 游标及实例(四)
- 现代操作系统 第一章 引论 习题
- java简单计算器课程设计_简单计算器JAVA课程设计
- keil4.72添加GD32F10x芯片
- 随机数生成器Random类
- 非匿名方式访问远程的com+
- JAVA大数据的第五十九天——The authenticity of host ‘gree129 (192.168.**.129)‘ can‘t be established.
- 合肥轨道交通线路图(2025+ / 运营版)
- AOP框架Aspects原理解析
- 指北针分类信息软件 高效稳定建立SEO外部链接