首页 技术 正文
技术 2022年11月21日
0 收藏 435 点赞 4,665 浏览 1502 个字

题意:给出两个单词,以及一个set集合,当中是很多的单词。unordered_set是无序的集合,也就是说找的序列也是无序的了,是C++11的标准,可能得升级你的编译器版本了。要求找出一个从start到end这两个单词的变换序列。从start开始,每次可以变一个字母,且所变之后的单词必须在set中,最后要求变成end,问经过了多少个中间变换?注意要加多2次(start和end也要算),这是规定。

思路:广度搜索,以start为树根,一层一层扩展,直到找到end,返回数的深度即可。步骤是这样的,先画出树根start,遍历set,所有能被start够经过1个字母的变换得到的,取出来(要删掉)做为第二层,也就是作为树根的孩子。接着以第二层的每个元素为起点,继续遍历set中的元素,直到搜到end,计算深度返回。

注:千辛万苦用g++的4.8.1版才能编译测试,网传可以用对当前单词的每个字母用a~z每个字母代替一次,再在set中查找出来,这个方法感觉看不出优势,n个单词,单词长为k,最差大概n*k*26次。下面这个是n*k。很累没有详细验证,大概就这样吧。搞了3天,才知道被那个for括号中第二个式子给玩坏了,它每次循环都会检查,也就是更新界限。

 class Solution {
public:
bool mat(string &lef,const string &rig) /*返回两个字符串是否匹配(允许一个字母不匹配)*/
{
int count=;
for(int i=; i<lef.size(); i++)
{
if(lef[i]!=rig[i])
{
count++;
if(count>=) return false;
}
}
return true; //不可能出现相等的,即count=0的情况
} int ladderLength(string start, string end, unordered_set<string> &dict) {
if( start.empty() || end.empty() || start==end || start.length() != end.length() ) return ;
if( mat(start,end) ) return ; //只有一个不匹配
if( dict.find(end) == dict.end() ) dict.insert(end);//end必须在set中
if( dict.find(start)!=dict.end() ) dict.erase(start); //start必须不在setzhong
unordered_set<string>::iterator dist = dict.find(end); //终点指针
unordered_set<string>::iterator it = dict.begin();
queue<string> que;
que.push(start); //起点先进队
int count=;
while(!que.empty())
{
count++;
int q=que.size(); //注意这里,不能将que.size()放在下一行的括号中代替q,它每次循环都检查一遍
for(int i=; i<q; i++) //此for扫描同一层的元素
{
it = dict.begin();
while( it!=dict.end() ) //搜dict中每个元素
{
if( mat( que.front(), *it) )
{
if( it == dist ) return count; //找到终点end
que.push(*it);
it = dict.erase(it); //在集合中删去
}
else it++;
}
que.pop();
}
}
return ;
}
};

word ladder

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,075
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,551
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,399
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,811
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,893