[LeetCode][JavaScript]Word Ladder

https://leetcode.com/problems/word-ladder/

Word Ladder

Given two words (beginWord and endWord), and a dictionary, 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 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.


果然js不适合做题么,缺少各种通用方法。

这题挂了无数次啊,一开始错把入参当做Array,其实是个Set,之后就一直超时...

bfs的思路是没错的,但首先不能构造图,复杂度O(n^2) 肯定不行。

然后尝试直接在Set里找,找到一个删除一个,也是超时。

最后只能换成了现在的方式。

这道题test case有特殊性,dict里的单词不会特别长,但是数据量很大。

于是最终改成在bfs队列中出队一个元素,一个个地用a-z替换每个字母,然后去跟字典比较。

 1 /**
 2  * @param {string} beginWord
 3  * @param {string} endWord
 4  * @param {set<string>} wordDict
 5  * @return {number}
 6  */
 7 var ladderLength = function(beginWord, endWord, wordDict) {
 8     var queue = [];
 9     var i = 0;
10     queue.push(beginWord);
11     wordDict.delete(beginWord);
12     if(oneCharDiff(beginWord, endWord) && wordDict.has(endWord)){
13         return 2;
14     }else{
15         return bfs();
16     }
17
18     function bfs(){
19         var depth = 1;
20         while(queue.length > 0){
21             depth++;
22             var count = queue.length;
23             while(count--){
24                 var curr = queue.shift();
25                 if(oneCharDiff(curr, endWord) && curr !== beginWord){
26                     return depth;
27                 }
28                 var needRemove = [];
29                 for(var i = 0; i < curr.length; i++){
30                     for(var j = ‘a‘.charCodeAt(); j <= ‘z‘.charCodeAt(); j++){
31                         var testMatch = curr;
32                         var ch = String.fromCharCode(j);
33                         if(testMatch[i] !== ch){
34                             testMatch = replaceChat(testMatch, i, ch);
35                         }
36                         if(wordDict.has(testMatch)){
37                             queue.push(testMatch);
38                             wordDict.delete(testMatch);
39                         }
40                     }
41                 }
42             }
43         }
44
45         return 0;
46     }
47     function isStrInArr(str, arr){
48         for(var i in arr){
49             if(str === arr[i]){
50                 return true;
51             }
52         }
53         return false;
54     }
55     function replaceChat(source, pos, newChar){
56         var sFrontPart = source.substr(0, pos);
57         var sTailPart = source.substr(pos + 1, source.length);
58         return sFrontPart + newChar + sTailPart;
59     }
60     function oneCharDiff(a, b){
61         if(a.length !== b.length){
62             return false;
63         }
64         var count = 0;
65         for(var i = 0; i < a.length; i++){
66             if(a[i].toLowerCase() !== b[i].toLowerCase()){
67                 count++;
68             }
69             if(count >= 2){
70                 return false;
71             }
72         }
73         if(count === 1){
74             return true;
75         }else{
76             return false;
77         }
78     }
79 };
时间: 2024-10-29 19:09:56

[LeetCode][JavaScript]Word Ladder的相关文章

LeetCode OJ - Word Ladder 2

我发现在leetcode上做题,当我出现TLE问题时,往往是代码有漏洞,有些条件没有考虑到,这道题又验证了我这一想法. 这道题是在上一道的基础上进一步把所有可能得转换序列给出. 同样的先是BFS,与此同时需要一个hashMap记录下每个节点,和他所有父节点的对应关系,然后通过DFS,回溯所有可能的路径. 下面是AC代码. 1 /** 2 * Given two words (start and end), and a dictionary, find all shortest transform

LeetCode OJ - Word Ladder

我觉得这道题比较难,主要是因为对于我来说: 1. 我没有把这个问题联想到树的宽度遍历(即便没有考虑树的宽度遍历,也是可以做的,但是我一开始实现的代码却是深度遍历,后来发现树的BFS一般使用queue实现的,貌似没有递归的方法??) 2. 即使在意识到用BFS,却还有一个陷阱:我是对字典进行了BFS,这个说实话,代码长,还TLE: 后来参考了前辈的代码,采用对26个单词进行枚举,才解决了这个问题. 下面是AC代码: 1 /** 2 * Given two words (start and end)

[LeetCode] 126. Word Ladder II_Hard tag: BFS&amp;DFS

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note

【LeetCode】Word Ladder 字符串

题目:Word Ladder <span style="font-size:18px;">/**LeetCode word ladder * 题目:给定一个起始单词和一个终结单词以及一个字典,要求每次变换一个字符,成为字典中新的词,直到变为最后的词,要求其最短路径 * 思路:利用队列,先弹出第一个词,分别将词中每一个字符替换直到找到一个字典中存在的词,加入队列,直到匹配的词是最后一个,此时终止 * 如果没有这样的路径,则返回0 */ package javaTrain; i

[Leetcode][JAVA] Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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

Leetcode 127. Word Ladder

思路: 1 class Solution(object): 2 def __init__(self): 3 return 4 5 def ladderLength(self, beginWord, endWord, wordList): 6 """ 7 :type beginWord: str 8 :type endWord: str 9 :type wordList: List[str] 10 :rtype: int 11 """ 12 fro

[LeetCode][JavaScript]Word Pattern

Word Pattern Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a substring in str. Examples: pattern = "abba", str = "dog c

[Leetcode][JAVA] 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

leetcode 127. Word Ladder ----- java

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 li