zoukankan      html  css  js  c++  java
  • [leedcode 126] 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.

    public class Solution {
        public int ladderLength(String beginWord, String endWord, Set<String> wordDict) {
            //BFS,利用队列保存在dict中出现的单词,并且记录level和count,从队列中取出每一个字符串,对字符串的每一位进行替换,如果存在于dict就添加         //到队列里,并且从dict删除 超时TLE
            if(beginWord.length()!=endWord.length())return 0;
            LinkedList<String> queue=new LinkedList<String>();
            queue.add(beginWord);
            int level=1;
            int count=1;
            wordDict.remove(beginWord);
            while(!queue.isEmpty()&&wordDict.size()>0){
              while(count>0){
                String word=queue.remove();
                count--;
                StringBuilder temp=new StringBuilder(word);
                for(int i=0;i<word.length();i++){
                    for(char j='a';j<='z';j++){
                        if(word.charAt(i)==j)continue;
                        char s=temp.charAt(i);
                        temp=temp.replace(i,i+1,j+"");
                        if(temp.equals(endWord)) return level+1;
                        if(wordDict.contains(temp.toString()))
                         {
                                queue.add(temp.toString());
                                wordDict.remove(temp.toString());
                         }
                        temp.replace(i,i+1,s+"");
                    }
                }
              }
             
             count=queue.size();
             level++;
            }
            return 0;
        }
    }
  • 相关阅读:
    「疫期集训day11」沙漠
    「树形DP」洛谷P2607 [ZJOI2008]骑士
    「疫期集训day10」玫瑰
    「疫期集训day9」七月
    核心容器(概念)
    初识Spring
    IOC(控制反转思想)原型理论推导
    图片在上,文字在下并且等间距的三个菜单按钮
    编写登陆接口
    001使用gltf创建3d模型
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4674705.html
Copyright © 2011-2022 走看看