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 };
  • 相关阅读:
    Fiddler-常用技巧
    Fiddler-工作原理
    C语言-EOF和feof()判断文件结尾的区别
    C语言-一个fopen函数中未使用二进制模式(b)引发的血案
    VIM-不常用或不知道的技巧
    C语言-srand种子详解
    C语言-字符串操作函数
    C语言-Makefile经典教程(掌握这些足够)
    分布拟合——正态/拉普拉斯/对数高斯/瑞利 分布
    曲线拟合——(2)拉普拉斯/瑞利/对数正态 曲线
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4780084.html
Copyright © 2011-2022 走看看