leetcode--Word Ladder

Problem Description:

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.

         分析:根据题目的意思,我首先想到的是利用DFS每次查找到与当前string距离为1的string, 用map来标记每次遍历过的string,下次不再比较, 然后继续往下搜索,直到找到目标string,记录下距离len,然后与当前最短距离min比较,更新min,最后运行的结果是超时。后来在网上查了一下,才发现是用BFS,而且我的代码中没有充分利用set查找时间复杂度是O(1)的特性,每次都遍历map比较的时间复杂度达到O(mn),其中m是字符串长度,n是set的元素个数。原始代码记录一下:

class Solution {
public:
    
    bool distance(string a,string b)
    {
        int dist=0;
        for(int i=0;i<a.size();++i)
        {
            if(a[i]!=b[i])
            dist++;
        }
        if(dist==1)
            return true;
        else
            return false;
    }
    
    bool dfs(string start,string end,map<string,bool> &flag,int &res,int &min)
    {
        if(start==end)
        {
            if(res<min)
                min=res;
            return true;
        }
        
        for(map<string,bool>::iterator i=flag.begin();i!=flag.end();++i)
        {
            if((*i).second==true&&distance(start,(*i).first))
            {
                res++;
                (*i).second=false;
                dfs((*i).first,end,flag,res,min);
                (*i).second=true;
                res--;
            }
        }
        return false;
    }
    
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        int res=0;
        int len=dict.size();
        if(len==0||start==end)
            return 0;
        int min=dict.size()+1;
        map<string,bool> flag;
        for(unordered_set<string>::iterator iter=dict.begin();iter!=dict.end();++iter)
            flag.insert(make_pair(*iter,true));
        bool tag=false;
        tag=dfs(start,end,flag,res,min);
        if(tag)
            return min+1;
        else
            return 0;
        
        
    }
};
Submission Result: Time Limit Exceeded

       利用BFS遍历的代码如下:
class Solution {
public:
    
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        int res=0;
        if(start==end||dict.size()==0)
            return res;
        unordered_set<string> midstr;//记录层次遍历的string,防止循环搜索
        queue<string> strque;
        strque.push(start);
        int lev=1,count=0; //用于记录队列每层的元素个数
        while(!strque.empty())
        {
            lev--;
            string str=strque.front();
            strque.pop();
            if(str==end)
            {
                res++;
                break;
            }
            
            midstr.insert(str);
            for(int i=0;i<str.size();++i)
                for(char ch='a';ch<='z';++ch)
                {
                    string temp=str;
                    if(str[i]==ch)
                        continue;
                    temp[i]=ch;
                        
                    if(dict.count(temp)==1&&midstr.count(temp)==0)
                    {
                        
                        count++;
                        strque.push(temp);
                        midstr.insert(temp);
                    }
                }
            if(lev==0)//当前层遍历完毕
            {
                res++;
                lev=count;
                count=0;
            }
        }
 
        if(res==1)//如果是1说明不存在路径,按照题目的设置,没有路径为1的情况
            return 0;
        else
            return res;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LeetCode-Editor是一种在线编码工具,它提供了一个用户友好的界面编写和运行代码。在使用LeetCode-Editor时,有时候会出现乱码的问题。 乱码的原因可能是由于编码格式不兼容或者编码错误导致的。在这种情况下,我们可以尝试以下几种解决方法: 1. 检查文件编码格式:首先,我们可以检查所编辑的文件的编码格式。通常来说,常用的编码格式有UTF-8和ASCII等。我们可以将编码格式更改为正确的格式。在LeetCode-Editor中,可以通过界面设置或编辑器设置来更改编码格式。 2. 使用正确的字符集:如果乱码是由于使用了不同的字符集导致的,我们可以尝试更改使用正确的字符集。常见的字符集如Unicode或者UTF-8等。在LeetCode-Editor中,可以在编辑器中选择正确的字符集。 3. 使用合适的编辑器:有时候,乱码问题可能与LeetCode-Editor自身相关。我们可以尝试使用其他编码工具,如Text Editor、Sublime Text或者IDE,看是否能够解决乱码问题。 4. 查找特殊字符:如果乱码问题只出现在某些特殊字符上,我们可以尝试找到并替换这些字符。通过仔细检查代码,我们可以找到导致乱码的特定字符,并进行修正或替换。 总之,解决LeetCode-Editor乱码问题的方法有很多。根据具体情况,我们可以尝试更改文件编码格式、使用正确的字符集、更换编辑器或者查找并替换特殊字符等方法来解决这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值