Word Ladder

Total Accepted: 10243 Total
Submissions: 58160My Submissions

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such
that:

  1. Only one letter can be changed at a time
  2. 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.

Have you been asked this question in an interview?

Yes

此题是图的遍历问题。要找一条起始点到目标点最短的路径,假设存在这种路径则返回路径长度。否则返回0。 刚開始想到用深度优先搜索遍历,可是时间复杂度太大。于是转为用宽搜,把起始点放入队列中,队列中的节点是一个字符串。由于要找到最短路径,所以在取出队首节点时要知道该节点属于第几层被搜索的节点,即路径长度,我用了levels来保存当前遍历的是第几层的节点,然后扩展该节点,把编辑距离为1而且在字典中出现的字符串增加队尾。并从字典中删除该字符串。

在找编辑距离为1的字符串时,我试了两种方法,一种是遍历字典,找到编辑记录为1的字符串,假设字典数目非常大的话,每次都遍历字典耗时太多了。结果就是TLE,后来直接对节点字符串进行改动一个字符来得到扩展字符串才通过。

<span style="font-size:14px;">class Solution {
public:
typedef queue<string,deque<string>> qq;
int ladderLength(string start, string end, unordered_set<string> &dict) {
//Use queue to implement bfs operation
qq q;
q.push(start);
dict.erase(start); int currLevelLens = 1, nextLevelLens;
int levels = 1; //To be returned answer, the total bfs levels be traversed
string front, str; while (!q.empty()) {
nextLevelLens = 0;
while (currLevelLens--) { // Traverse the node of current level
string front = q.front();
q.pop();
if (front == end)
return levels;
for (int i=0; i<front.size(); ++i) {
for (char j='a'; j<='z'; ++j) { // transform
if (front[i]=='j')
continue;
str = front;
str[i] = j;
if (dict.find(str) != dict.end()) {
++nextLevelLens;
q.push(str);
dict.erase(str);
}
}
}
}
currLevelLens = nextLevelLens;
++levels;
}
return 0;
} };
</span>

可是这个方案改变了dict的内容。有没有不改变dict的方法呢?我试了用一个unorder_set来保存被搜索过的字符串,可是耗时比前一种方法多。

class Solution {
public:
typedef queue<string,deque<string>> qq;
int ladderLength(string start, string end, unordered_set<string> &dict) {
//Use queue to implement bfs operation
qq q;
q.push(start); int currLevelLens = 1, nextLevelLens;
int levels = 1; //To be returned answer, the total bfs levels be traversed
string front, str;
searchedStrs.insert(start);
while (!q.empty()) {
nextLevelLens = 0;
while (currLevelLens--) { // Traverse the node of current level
string front = q.front();
q.pop();
if (front == end)
return levels;
for (int i=0; i<front.size(); ++i) {
for (char j='a'; j<='z'; ++j) { // transform
if (front[i]==j)
continue;
str = front;
str[i] = j; if (searchedStrs.find(str) == searchedStrs.end() && dict.find(str) != dict.end()) {
++nextLevelLens;
q.push(str);
//dict.erase(str);
searchedStrs.insert(str);
}
}
}
}
currLevelLens = nextLevelLens;
++levels;
}
return 0;
}
private:
unordered_set<string> searchedStrs;
};

Python解法:

有參考Google Norvig的拼写纠正样例:http://norvig.com/spell-correct.html

class Solution:
# @param word, a string
# @return a list of transformed words
def edit(self, word):
alphabet = string.ascii_lowercase
splits = [(word[:i],word[i:]) for i in range(len(word)+1)]
replaces = [a+c+b[1:] for a,b in splits for c in alphabet if b]
replaces.remove(word)
return replaces # @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
currQueue = []
currQueue.append(start)
dict.remove(start)
ret = 0
while 1:
ret += 1
nextQueue = []
while len(currQueue):
s = currQueue.pop(0)
if s == end:
return ret
editWords = self.edit(s) for word in editWords:
if word in dict:
dict.remove(word)
nextQueue.append(word)
if len(nextQueue)==0:
return 0
currQueue = nextQueue
return 0

leetcode-WordLadder的更多相关文章

  1. leetcode — word-ladder

    import java.util.*; /** * Source : https://oj.leetcode.com/problems/word-ladder/ * * * Given two wor ...

  2. [LeetCode] Word Ladder 词语阶梯

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

  3. leetcode算法分类

    利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...

  4. LeetCode题目分类

    利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...

  5. 【LeetCode OJ】Word Ladder II

    Problem Link: http://oj.leetcode.com/problems/word-ladder-ii/ Basically, this problem is same to Wor ...

  6. 【LeetCode OJ】Word Ladder I

    Problem Link: http://oj.leetcode.com/problems/word-ladder/ Two typical techniques are inspected in t ...

  7. <转>LeetCode 题目总结/分类

    原链接:http://blog.csdn.net/yangliuy/article/details/44514495 注:此分类仅供大概参考,没有精雕细琢.有不同意见欢迎评论~ 利用堆栈:http:/ ...

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

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

  9. [LeetCode]题解(python):127-Word Ladder

    题目来源: https://leetcode.com/problems/word-ladder/ 题意分析: 和上一题目类似,给定一个beginWord和一个endWord,以及一个字典list.这题 ...

  10. LeetCode 题目总结/分类

    LeetCode 题目总结/分类 利用堆栈: http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ http://oj.l ...

随机推荐

  1. VBA开发经验总结之二:灵活运用工作表属性

    近期,在帮公司写一个销售管理的工具,高强度的开发激发了我对一些以前既有方式的看法,特将几点开发经验总结在此. 1.将工作表及窗体的公共变量及特征变量写为工作表或窗体的属性.此种方法的优点: ① 采用面 ...

  2. js中的forin

    前言 自己在平时没事干练练手,发现的以前一直以为是错的.幸亏今天知道了,要不说起来自己还不知道呢. 过程 遍历前置页面上的textbox,给他们赋值(js). 一开始自己用forin遍历的. 如论如何 ...

  3. js中的prototye

    前言 没事的时候写着js完,一般可能大家都知道这个属性吧,但是我还要说说,给一些不知道的人看看吧, 希望对你有帮助. 过程 以前在学c#的时候,老师最多用的就是Person这个类来开讲,我觉得是这个更 ...

  4. php中遇到include_path='.;C:\php5\pear'的错误

    所有面页,包括空白的都会报类似下面的错误. Warning: Unknown: failed to open stream: No such file or directory in Unknown  ...

  5. 帝国cms7.0修改“信息提示”框

    具体修改查看e/message/index.php文件 上传一张合适用的图 <table width="600" height="224" border= ...

  6. PM【terminal】

    More Knowledge More Performance More Time 资料模组化 以知识管理为基础的项目管理 规范:ethic

  7. 学习Swift--属性

    属性 属性将值跟特定的类.结构或枚举关联.存储属性存储常量或变量作为实例的一部分,而计算属性计算(不是存储)一个值.计算属性可以用于类.结构体和枚举,存储属性只能用于类和结构体. 存储属性和计算属性通 ...

  8. JS贪吃蛇游戏

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...

  9. [BZOJ 1025] [SCOI2009] 游戏 【DP】

    题目链接:BZOJ - 1025 题目分析 显然的是,题目所要求的是所有置换的每个循环节长度最小公倍数的可能的种类数. 一个置换,可以看成是一个有向图,每个点的出度和入度都是1,这样整个图就是由若干个 ...

  10. Cocos2d-x 2.0以上版本安装方法

    1,cd 到2dx根目录,MAC平台使用./create-multi-platform-projects.py  然后提示: -bash: ./create-multi-platform-projec ...