zoukankan      html  css  js  c++  java
  • leetcode25word-ladder

    题目描述

    给定两个单词(初始单词和目标单词)和一个单词字典,请找出所有的从初始单词到目标单词的最短转换序列的长度:
    1. 每一次转换只能改变一个单词
    2. 每一个中间词都必须存在单词字典当中
    例如:
    给定的初始单词start="hit",
    目标单词end ="cog"。
    单词字典dict =["hot","dot","dog","lot","log"]
    一个最短的转换序列为"hit" -> "hot" -> "dot" -> "dog" -> "cog",
    返回长度5

    注意:
    如果没有符合条件的转换序列,返回0。
    题目中给出的所有单词的长度都是相同的
    题目中给出的所有单词都仅包含小写字母

    Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, 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 length5.

    Note:

      • Return 0 if there is no such transformation sequence.
      • All words have the same length.
        class Solution {
        public:
            int ladderLength(string start, string end, unordered_set<string> &dict) {
                queue<string>Q;
                Q.push(start);
                int res=1;
                while (!Q.empty()){
                    int qsize=Q.size();
                    while (qsize--){
                        string cur_front=Q.front();
                        Q.pop();
                        int size=cur_front.size();
                        for (int i=0;i<size;i++)
                        {
                            char ch=cur_front[i];
                            for (int j=0;j<26;j++){
                                cur_front[i]='a'+j;
                                if (cur_front==end) return res+1;
                                if (dict.find(cur_front)!=dict.end())
                                {
                                    Q.push(cur_front);
                                    dict.erase(cur_front);
                                }
                            }
                            cur_front[i]=ch;
                        }
                    }
                    res++;
                }
                return 0;
            }
        };
  • 相关阅读:
    robots.txt
    procdump和mimikatz工具配合破解windows账户口令
    通过vbs脚本控制方向盘按键
    批处理删除文件或文件夹代码
    彩色线条雨特效html代码
    secureCRT
    chrome 更新flash插件
    python命令行下安装redis客户端
    FastJson使用
    Redis 学习(二)
  • 原文地址:https://www.cnblogs.com/hrnn/p/13408196.html
Copyright © 2011-2022 走看看