【Leetcode】127. Word Ladder(字符串阶梯)

╰+哭是因爲堅強的太久メ 2022-02-04 13:27 307阅读 0赞

Given two words (beginWord and endWord), and a dictionary’s word list, 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 transformed word must exist in the word list. Note that beginWord is nota transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

  1. Input:
  2. beginWord = "hit",
  3. endWord = "cog",
  4. wordList = ["hot","dot","dog","lot","log","cog"]
  5. Output: 5
  6. Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
  7. return its length 5.

Example 2:

  1. Input:
  2. beginWord = "hit"
  3. endWord = "cog"
  4. wordList = ["hot","dot","dog","lot","log"]
  5. Output: 0
  6. Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

题目大意:

给出开始和结束字符串,同时给出一个字符串字典,字典中所有的字符串都是不重复等长的。每次从上一个字符串只变动一个字节。求出最短次数,从beginWord到endWord。

解题思路:

DFS容易陷入无用的循环中,结果超时。应该使用BFS,将wordList转化为字典,没找到一个下一个符合的字符串,就要通过本位置的’a’-‘z’找出全部的符合条件的字符串加入queue。

  1. class Solution {
  2. public:
  3. int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
  4. // BFS
  5. unordered_set<string> dict(wordList.begin(), wordList.end());
  6. queue<string> todo;
  7. todo.push(beginWord);
  8. int ladder=1;
  9. while(!todo.empty()){
  10. int n = todo.size();
  11. for(int i=0;i<n;i++){
  12. string word = todo.front();
  13. todo.pop();
  14. if(word == endWord){
  15. return ladder;
  16. }
  17. dict.erase(word);
  18. for(int j=0;j<word.size();j++){
  19. char c=word[j];
  20. for(int k=0;k<26;k++){
  21. word[j] = 'a'+k;
  22. if(dict.find(word)!=dict.end()){
  23. todo.push(word);
  24. }
  25. }
  26. word[j]=c;
  27. }
  28. }
  29. ladder++;
  30. }
  31. return 0;
  32. }
  33. };

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Word Ladder--LeetCode

    这道题看似一个关于字符串操作的题目,其实要解决这个问题得用图的方法。我们先给题目进行图的映射,顶点则是每个字符串,然后两个字符串如果相差一个字符则我们进行连边。接下来看看这个方