前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >程序员面试金典 - 面试题 17.22. 单词转换(BFS)

程序员面试金典 - 面试题 17.22. 单词转换(BFS)

作者头像
Michael阿明
发布2020-07-13 15:39:45
5810
发布2020-07-13 15:39:45
举报

1. 题目

给定字典中的两个词,长度相等。 写一个方法,把一个词转换成另一个词, 但是一次只能改变一个字符。 每一步得到的新词都必须能在字典中找到。

编写一个程序,返回一个可能的转换序列。如有多个可能的转换序列,你可以返回任何一个。

代码语言:javascript
复制
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
输出:
["hit","hot","dot","lot","log","cog"]

示例 2:
输入:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
输出: []
解释: endWord "cog" 不在字典中,所以不存在符合要求的转换序列。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/word-transformer-lcci 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

类似题目: LeetCode 126. 单词接龙 II(图的BFS) LeetCode 127. 单词接龙(图的BFS/双向BFS)

  • 广度优先搜索
代码语言:javascript
复制
class Solution {
public:
    vector<string> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        vector<string> ans, frontPath, newpath;
        int len = wordList.size(), i, k, n, lv = 0;
        unordered_map<string,int> m;
        vector<bool> visited(len,false);
        for(i = 0; i < len; ++i)
        {
            m[wordList[i]] = i;
            if(wordList[i] == beginWord)
                visited[i] = true;
        }
        if(m.find(endWord) == m.end())
        	return {};
        queue<vector<string>> q;
        frontPath.push_back(beginWord);
        q.push(frontPath);
        string str;
        while(!q.empty())
        {
        	lv++;
        	n = q.size();
        	while(n--)
        	{
                frontPath = q.front();
                q.pop();
	        	for(i = 0; i < beginWord.size(); ++i)
	        	{//对每个单词的每个字符进行改变
                    str = frontPath.back();
                    for(k = 1; k <= 25; ++k)
                    {
    	        		str[i] += 1;
    	        		if(str[i] > 'z')
    	        			str[i] = 'a';
    	        		if(m.find(str) != m.end() && !visited[m[str]])
    	        		{	//在集合中,且没有访问的
                            newpath = frontPath;
    	        			newpath.push_back(str);
                            q.push(newpath);
    	        			visited[m[str]] = true;
    	        			if(str == endWord)
            					return newpath;
    	        		}
                    }
	        	}
	        }
        }
        return {};
    }
};

308 ms 19.4 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/04/11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档