zoukankan      html  css  js  c++  java
  • 【题解】【字符串】【BFS】【Leetcode】Word Ladder

    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.

    思路:

    字符串的花儿挺多,word ladder也是CC150 v5上的18.10题,乍一看无从下手,其实就是BFS求单源无权最短路径。

    想要大set不超时,关键有几点:

    1. 一边加新词进queue,一边从dict里remove掉

    2. 直接寻找所有可能的OneEditWords判断是否在dict里面,每次都过一遍dict一个一个判断是否为OneEditWords会超时。我还有一个超时的方法,就是寻找所有可能的OneEditWords再建一个unordered_set跟dict求交集,后来发现algoritm里的set_intersection只支持两个有序集合很坑,需要先把unordered_set转化为vector排序,结果不言而喻。

    3. 将unordered_map<string, int > path并到访问队列qwords里去会跑得更快,反正这里不要求输出路径,这个可以做下优化

    4. 将getOneEditWords这个函数并到ladderLength里头会跑得更快,不过我觉得可读性会降低

     1 int ladderLength(string start, string end, unordered_set<string> &dict) {
     2     unordered_set<string> ndict(dict);//最好不要修改输入参数
     3     queue<string> qwords;//BFS访问队列
     4     unordered_map<string, int > path;//记录到start的最短路径,其实可以并入qwords中
     5     
     6     qwords.push(start);
     7     path[start] = 1;
     8     ndict.erase(start);
     9     
    10     while(!qwords.empty()){
    11         start = qwords.front();
    12         qwords.pop();
    13         int len = path[start];
    14         for(string s :getOneEditWords(start)){//边局部构建map,边处理
    15             if(ndict.find(s) == ndict.end()) continue;//一个一个判断dict中元素是否为OneEditWords会超时
    16             if(s == end) return len+1;
    17             qwords.push(s);
    18             path[s] = len+1;
    19             ndict.erase(s);//如果不erase访问过的元素会超时
    20         }
    21     }
    22     return 0;    
    23 } 
    24 
    25 vector<string> getOneEditWords(string start){
    26     vector<string> words;
    27     for(unsigned int i = 0; i < start.size(); i++){
    28         string word(start);
    29         for(char ch = 'a'; ch <= 'z'; ch++){
    30             if(ch != start[i]){
    31                 word[i] = ch;
    32                 words.push_back(word);
    33             }
    34         }
    35     }
    36     return words;      
    37 }

     

     

  • 相关阅读:
    python
    python
    Django+Scrapy结合使用并爬取数据入库
    python--scrapy框架爬取分页数据与详情页数据
    python--简单的jQuery-Ajax使用
    python--scrapy框架配置redis数据库或者mongdb数据库
    ajax分页
    django分页
    Jquery获取输入框属性file,ajax传输后端,下载图片
    Django中web开发用md5加密图片名并存储静态文件夹
  • 原文地址:https://www.cnblogs.com/wei-li/p/WordLadder.html
Copyright © 2011-2022 走看看