题目:

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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWordis not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"] Output: 5 Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"] Output: 0 Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

分析:

给定起始和终止两个单词,和一个单词列表,要求我们使用列表中的单词将起始和终止单词连接起来,连接的规则是要求每次只改变一个字符,且在列表中存在,终止单词也需要在列表中。

我们可以利用广度优先搜索,从起始单词开始,将每一位字符从a到z依次改变,如果改变后的单词在列表中,就记录下来,并在集合中删去,这样做的目的是为了防止重复的搜索,例如dog-dop-dog,这样是浪费时间的,当新加入的单词和最终单词相同时,返回步骤数即可,如果保存搜索单词的集合(队列)为空时,证明已经搜索结束,且没有找到,返回0即可。

还可以利用双向广度优先搜索进行优化,思想就是同时从起始单词和终止单词开始搜索,也是通过改变字符,且在单词列表中便加入到两个搜索集中,当一侧搜索出来的单词,在另一侧的搜索单词集中,意味着出现了解。至于搜索的次序,如果当一方的集合中的单词数量小于另一方时,就优先从数量小的集合开始搜索。

程序:

C++

class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
//set<string> dict;
unordered_set<string> dict;
for(string s:wordList)
dict.insert(s);
if(dict.count(endWord) == )
return ;
queue<string> q;
q.push(beginWord);
int l = beginWord.length();
int step = ;
while(!q.empty()){
step++;
int len = q.size();
for(int i = ; i < len; ++i){
string word = q.front();
q.pop();
for(int j = ; j < l; ++j){
char ch = word[j];
for(int k = 'a'; k <= 'z'; ++k){
if(k == ch)
continue;
word[j] = k;
if(word == endWord)
return step+;
if(dict.count(word) == )
continue;
q.push(word);
dict.erase(word);
}
word[j] = ch;
}
}
}
return ;
}
};
//Bidirectional BFS
//Runtime: 28 ms, faster than 98.16% of C++ online submissions for Word Ladder.
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
//set<string> dict;
unordered_set<string> dict;
for(string s:wordList)
dict.insert(s);
if(dict.count(endWord) == )
return ;
unordered_set<string> q1;
unordered_set<string> q2;
q1.insert(beginWord);
q2.insert(endWord);
int l = beginWord.length();
int step = ;
while(!q1.empty() && !q2.empty()){
step++;
if(q1.size() > q2.size())
swap(q1, q2);
unordered_set<string> q;
for(string word:q1){
for(int j = ; j < l; ++j){
char ch = word[j];
for(int k = 'a'; k <= 'z'; ++k){
if(k == ch)
continue;
word[j] = k;
if(q2.count(word))
return step+;
if(dict.count(word) == )
continue;
q.insert(word);
dict.erase(word);
}
word[j] = ch;
}
}
swap(q, q1);
}
return ;
}
};

Java

class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet<>(wordList);
if(!dict.contains(endWord))
return 0;
Queue<String> q = new ArrayDeque<>();
q.offer(beginWord);
int l = beginWord.length();
int step = 0;
while(!q.isEmpty()){
step++;
int len = q.size();
for(int i = 0; i < len; ++i){
//String word = q.poll();
StringBuilder word = new StringBuilder(q.poll());
for(int j = 0; j < l; ++j){
char ch = word.charAt(j);
for(int k = 'a'; k < 'z'; ++k){
if(ch == k)
continue;
word.setCharAt(j, (char)k);
String w = word.toString();
if(w.equals(endWord))
return step+1;
if(!dict.contains(w))
continue;
q.offer(w);
dict.remove(w);
}
word.setCharAt(j, ch);
}
}
}
return 0;
}
}
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> dict = new HashSet<>(wordList);
if(!dict.contains(endWord))
return 0;
Set<String> q1 = new HashSet<>();
q1.add(beginWord);
Set<String> q2 = new HashSet<>();
q2.add(endWord);
int l = beginWord.length();
int step = 0;
while(!q1.isEmpty() && !q2.isEmpty()){
step++;
if(q1.size() > q2.size()){
Set<String> temp = q1;
q1 = q2;
q2 = temp;
}
Set<String> q = new HashSet<>();
for(String s:q1){
StringBuilder str = new StringBuilder(s);
for(int i = 0; i < l; ++i){
char ch = str.charAt(i);
for(int j = 'a'; j <= 'z'; ++j){
if(ch == j)
continue;
str.setCharAt(i, (char)j);
String word = str.toString();
if (q2.contains(word))
return step + 1;
if(!dict.contains(word))
continue;
dict.remove(word);
q.add(word);
}
str.setCharAt(i, ch);
}
}
q1.clear();
q1.addAll(q);
}
return 0;
}
}

LeetCode 127. Word Ladder 单词接龙(C++/Java)的更多相关文章

  1. [leetcode]127. Word Ladder单词接龙

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  2. [LeetCode] 127. Word Ladder 单词阶梯

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  3. 127 Word Ladder 单词接龙

    给出两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列,转换需遵循如下规则:    每次只能改变一个字母.    变换过程中的 ...

  4. leetcode 127. Word Ladder、126. Word Ladder II

    127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...

  5. Leetcode#127 Word Ladder

    原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...

  6. leetcode@ [127] Word Ladder (BFS / Graph)

    https://leetcode.com/problems/word-ladder/ Given two words (beginWord and endWord), and a dictionary ...

  7. leetcode 127. Word Ladder ----- java

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  8. [LeetCode] 127. Word Ladder _Medium tag: BFS

    Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...

  9. Java for LeetCode 127 Word Ladder

    Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformatio ...

随机推荐

  1. 面试时面试官想要听到什么答案(关于一些vue的问题)

    前言 自己也只是一个前端的小白,因为公司大佬都比较忙,面试这种事就落到了我这小白身上,第一次叫我去的时候我是百般拒绝的,因为自己还是有自知之明的,但是别人实在抽不开身,没办法只能去了,他们开玩笑说就按 ...

  2. 小白学 Python 爬虫(37):爬虫框架 Scrapy 入门基础(五) Spider Middleware

    人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...

  3. 【转】Hive Data Manipulation Language

    Hive Data Manipulation Language Hive Data Manipulation Language Loading files into tables Syntax Syn ...

  4. dp - LIS

    某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能超过前一发的高度.某天,雷达捕捉到敌国的导弹来袭.由于 ...

  5. newSQL 到底是什么?

    数据库发展至今已经有3代了: SQL,传统关系型数据库,例如 MySQL noSQL,例如 MongoDB newSQL SQL 的问题 互联网在本世纪初开始迅速发展,互联网应用的用户规模.数据量都越 ...

  6. synchronized的使用

    概念: 是利用锁的机制来实现同步的. 锁机制有如下两种特性: 互斥性:即在同一时间只允许一个线程持有某个对象锁,通过这种特性来实现多线程中的协调机制,这样在同一时间只有一个线程对需同步的代码块(复合操 ...

  7. .net mvc Bundle 自己配置

    遇到了个坑 来和大家分享一下 1.一个空的mvc项目需要引用 System.Web.Optimization 2.然后nuget添加 microsoft ASP.NET WEB OPTIMIZATIO ...

  8. RocketMQ 解决 No route info of this topic 异常步骤

    原文地址:https://blog.csdn.net/chenaima1314/article/details/79403113 rocketmq运行时提示 No route info of this ...

  9. java中常用的锁机制

    基础知识 基础知识之一:锁的类型 锁就那么几个,只是根据特性,分为不同的类型 锁的概念 在计算机科学中,锁(lock)或互斥(mutex)是一种同步机制,用于在有许多执行线程的环境中强制对资源的访问限 ...

  10. Java Web面试题整理(思维导图)

    1,动态网站技术有哪些? 2,一般的Web架构是指BS 还是CS,BS架构是什么咚咚? 3,Web应用程序的流程,即把一个URL串输入地址栏后发生写什么? 4,说一说Servlet生命周期? 5,在W ...