leetcode — word-ladder
import java.util.*;
/**
* Source : https://oj.leetcode.com/problems/word-ladder/
*
*
* 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.
*
*/
public class WordLadder {
/**
*
* 转化为图的问题
* start、end、dict中各个单词看做是图中的每个节点
* 如果有一个单词能变化一个字母到另外一个单词,说明两个节点是连通的
*
* 所以就转化为求两个节点之间的最短距离,使用BFS
*
* 使用BFS注意:
* 1. 找到当前需要遍历的节点,这里是当前节点的相邻节点
* 2. 标记已经遍历过的节点,防止从重复遍历
*
* 从start开始使用BFS,遍历当前节点的相邻节点,求出当前节点的相邻节点两种办法:
* 1. 遍历字典中每个单词,如果和当前单词只差一个字母,说明是相邻的,复杂度为:w*n,w是当前单词的长度,n是字典单词数量
* 2. 针对当前单词的每个字母,找出可能得变化,每个字母可以变为26个字母中除本身外的其他字母,如果判断变化后的单词在字典中则为相邻的节点,
* 复杂度为 26*w,w为单词长度
*
* 当字典中单词数量较小的时候可以使用第一种方法,如果字典中单词数量较大则使用第二种方法
*
* 怎么标记访问过的节点?
* 已经访问过的节点不需要再次被访问,所以可以从字典中删除
*
* 这里使用第二种方法
*
* @param start
* @param end
* @param dict
* @return
*/
public int ladderLength (String start, String end, String[] dict) {
Set<String> set = new HashSet<String>(Arrays.asList(dict));
set.add(end);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(start, 1);
while (map.size() > 0) {
String cur = map.keySet().iterator().next();
Integer len = map.get(cur);
if (cur.equals(end)) {
System.out.println(len);
// return len;
}
map.remove(cur);
Set<String> neighbors = findNeighbors(cur, set);
for (String str : neighbors) {
map.put(str, len+1);
}
}
return 0;
}
private Set<String> findNeighbors (String cur, Set<String> dict) {
Set<String> neighbors = new HashSet<String>();
for (int i = 0; i < cur.length(); i++) {
for (int j = 0; j < 26; j++) {
char ch = (char) ('a' + j);
if (cur.charAt(i) != ch) {
String candidate = "";
if (i == cur.length()-1) {
candidate = cur.substring(0, i) + ch;
} else {
candidate = cur.substring(0, i) + ch + cur.substring(i+1);
}
if (dict.contains(candidate)) {
neighbors.add(candidate);
dict.remove(candidate);
}
}
}
}
return neighbors;
}
public static void main(String[] args) {
WordLadder wordLadder = new WordLadder();
String start = "hit";
String end = "cog";
String[] dict = new String[]{"hot","dot","dog","lot","log"};
System.out.println(wordLadder.ladderLength(start, end, dict) + "----5");
}
}
leetcode — word-ladder的更多相关文章
- LeetCode:Word Ladder I II
其他LeetCode题目欢迎访问:LeetCode结题报告索引 LeetCode:Word Ladder Given two words (start and end), and a dictiona ...
- [leetcode]Word Ladder II @ Python
[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://b ...
- [LeetCode] Word Ladder 词语阶梯
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...
- [LeetCode] Word Ladder II 词语阶梯之二
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- LeetCode :Word Ladder II My Solution
Word Ladder II Total Accepted: 11755 Total Submissions: 102776My Submissions Given two words (start ...
- LeetCode: Word Ladder II 解题报告
Word Ladder II Given two words (start and end), and a dictionary, find all shortest transformation s ...
- LeetCode: Word Ladder II [127]
[题目] Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) ...
- LeetCode Word Ladder 找单词变换梯
题意:给出两个单词,以及一个set集合,当中是很多的单词.unordered_set是无序的集合,也就是说找的序列也是无序的了,是C++11的标准,可能得升级你的编译器版本了.要求找出一个从start ...
- [leetcode]Word Ladder @ Python
原题地址:https://oj.leetcode.com/problems/word-ladder/ 题意: Given two words (start and end), and a dictio ...
- Leetcode Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequen ...
随机推荐
- python 日常错误整理
1.NameError: name 'raw_input' is not defined 问题原因:python 3 中raw_input已经被input 替代
- 勾勾街:一个专业的苹果ios app 自助打包的网站,免越狱,免证书签名
众所周知,苹果的APP开发是需要基于MAC环境的,而我们很多的开发者并没有这样的条件,如果单单为发布一款app就去买一台价格昂贵的MAC那成本就太高了! 就算你有一台MAC,也有能力自己开发出一款基于 ...
- [zt]C++二维数组讲解、二维数组的声明和初始化
定义: int *pia = new int[10]; // array of 10 uninitialized ints 此 new 表达式分配了一个含有 10 个 int 型元素的数组,并返回指向 ...
- 解决挂载nfs共享目录失败的问题
现象:在192.168.82.131上 启动了nfs服务,并共享了/nfsfile目录,在另一台主机(ip: 192.1168.82.115)挂载的时候一直阻塞 1 初步分析是防火墙拦截导致,于是进行 ...
- SpringBoot报错:Table 'database_name.hibernate_sequence' doesn't exist
引起条件: SpringBoot+JPA插入包含自增字段的对象 @Id @GeneratedValue private Integer id; 解决方法: 给注解添加属性 @Id @Generated ...
- 做个流量站-聚茶吧, 汇聚"茶"的地方
犹豫了好久,终于下定决心,做一回个人站长了,虽然没啥经验,但毕竟也是IT科班出身了,准备用一年的事件摸索一下内容站和SEO,看看能否积累点经验,赚点小钱. 推酷-靠爬虫起家的内容站 做内容站,站长们都 ...
- layui select使用问题
1.需要引用form模板 layui.use(['form'], function () { var form = layui.form; }); 2.html代码 <div class=&qu ...
- 盒子模型/div标签/益出处理
/* <div></div>没有任何功能,不属于功能标签 可以放文字,图片以及各种元素的块标签 常常用来布局 span标签属于行内标签,无法设置宽高 */ <!docty ...
- C语言面试题分类->字符串处理
1.strlen:计算字符串长度(不包含'\0') 实现想法:遍历字符串,直到'\0'结束 #include<stdio.h> #include<stdlib.h> #incl ...
- JDK的下载,安装,环境变量配置
JDK 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/index.html 环境变量配置:在"系统变量" ...