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

    Note:

      • Return 0 if there is no such transformation sequence.
      • All words have the same length.
      • All words contain only lowercase alphabetic characters.

    Analyse: Refered to this

    Runtime: 276ms. 

     1 class Solution {
     2 public:
     3     int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
     4         wordDict.insert(endWord); //consider the string set as a graph
     5         queue<pair<string, int> > q;
     6         q.push(make_pair(beginWord, 1)); //start from the beginWord
     7         
     8         while(!q.empty()){
     9             string s = q.front().first; //string to be compared
    10             int result = q.front().second; //the length of the ladder
    11             
    12             if(s == endWord) return result; //reach to the last string
    13             q.pop();
    14             vector<string> neighbours = findNeighbours(s, wordDict); //find all neighbour string to the s
    15             for(int i = 0; i < neighbours.size(); i++)
    16                 q.push(make_pair(neighbours[i], result + 1));
    17         }
    18         return 0;
    19     }
    20     
    21     vector<string> findNeighbours(string s, unordered_set<string>& wordDict){
    22         vector<string> result;
    23         for(int i = 0; i < s.length(); i++){
    24             char temp = s[i];
    25             for(int j = 0; j < 26; j++){// O(26 * s.length())
    26                 if(temp == 'a' + j) continue; //if the character is the same, then move to the next character
    27                 s[i] = 'a' + j;
    28                 if(wordDict.find(s) != wordDict.end()){
    29                     result.push_back(s);
    30                     wordDict.erase(s);
    31                 }
    32             }
    33             s[i] = temp;
    34         }
    35         return result;
    36     }
    37 };
  • 相关阅读:
    玩个JAVA爬虫,没想玩大
    利用 Ruoyi 开发自己的业务管理系统__测试结构完成
    Vmware 和 VisualSVN-Server端口冲突
    Ruoyi的确不错,不知后续能否坚持 允许商用
    张勇:海底捞店长最高年薪600万!
    自己安装windows版本的Flink
    windows平台上运行Flink_转载于CSDN
    洛谷P3980 [NOI2008]志愿者招募
    线段树优化连边
    [HNOI2013]题解
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4780084.html
Copyright © 2011-2022 走看看