• 127. Word Ladder(js)


    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;
        
    };
  • 相关阅读:
    pam_cracklib module
    转:ubuntu svn
    fw: subversion+apache config
    转:jenkins 简介
    fw:java 10大必知技术
    FW: Linux 搭建 csvn 服务器。
    转:修改svn 端口号
    转:Ubuntu搭建jenkins
    转:vmware workstation的三种网络连接方式。
    图像处理之直方图均衡
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10909276.html
Copyright © 2020-2023  润新知