标签:one fun amp oss word 选择 short @param seq
127. Word Ladder
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:
Note:
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.
题意:单词接龙,给定初始单词和结束单词。每次只改变单词一个字符并且改变后的单词必须存在于单词列表(wordList)中,返回接龙数量最小的值
代码如下:
/** * @param {string} beginWord * @param {string} endWord * @param {string[]} wordList * @return {number} */ var ladderLength = function(beginWord, endWord, wordList) { let len=1; let queue=[beginWord]; let dict=new Set(wordList); let seen=new Set(queue); while(queue.length){ const next=[]; for(let v of queue){ if(v===endWord){ return len; } const arr=v.split(‘‘); // 暴力替换,对当前单词的所有字符进行替换 for(let i=0;i<arr.length;i++){ for(let c=0;c<26;c++){ arr[i]=String.fromCharCode(97+c); let nv=arr.join(‘‘); // 尚未选择的,并且存在于dict列表中的单词 if(!seen.has(nv) && dict.has(nv)){ next.push(nv); seen.add(nv); } arr[i]=v[i]; } } } queue=next; len++; } return 0; };
标签:one fun amp oss word 选择 short @param seq
原文地址:https://www.cnblogs.com/xingguozhiming/p/10909276.html