zoukankan      html  css  js  c++  java
  • leetcode

    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 length 5.

    Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.
    class Solution {
        public:
            int ladderLength(std::string start, std::string end, std::unordered_set<std::string> &dict) {
                std::unordered_map<std::string, int> dis;
                std::queue<std::string> q;
                dis[start] = 1;
                q.push(start);
                while (!q.empty()) {
                    std::string word = q.front(); q.pop();
                    if (word == end) break;
                    for (int i = 0; i < word.size(); i++) {
                        for (int j = 0; j < 26; j++) {
                            std::string newWord = word;
                            newWord[i] = 'a' + j;
                            if (dict.count(newWord) > 0 && dis.count(newWord) == 0) {
                                dis[newWord] = dis[word] + 1;
                                q.push(newWord);
                            }
                        }
                    }
                }
                if (dis.count(end) == 0) return 0;
                return dis[end];
            }
    };


  • 相关阅读:
    maven+spark2.0.0最大连通分量
    Eclipse+maven+scala2.11.8+spark2.0.0的环境部署
    杀死mapreduce
    filter-自己的理解
    JS变量声明提升
    js==运算符强制转换规则
    html 文字间距
    如你所见,我开始用微博
    vue数据模拟
    vue项目目录介绍
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5036493.html
Copyright © 2011-2022 走看看