码迷,mamicode.com
首页 > Web开发 > 详细

127. Word Ladder(js)

时间:2019-05-23 00:13:45      阅读:147      评论:0      收藏:0      [点我收藏+]

标签: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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is 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.
题意:单词接龙,给定初始单词和结束单词。每次只改变单词一个字符并且改变后的单词必须存在于单词列表(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;
    
};

 

127. Word Ladder(js)

标签:one   fun   amp   oss   word   选择   short   @param   seq   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10909276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!