单词接龙-LintCode

给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。
注意事项
如果没有转换序列则返回0。
所有单词具有相同的长度。
所有单词都只包含小写字母。
样例
给出数据如下:
start = “hit”
end = “cog”
dict = [“hot”,”dot”,”dog”,”lot”,”log”]
一个最短的变换序列是 “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
返回它的长度 5

#ifndef C120_H
#define C120_H
#include<iostream>
#include<string>
#include<vector>
#include<unordered_set>
#include<queue>
#include<map>
using namespace std;
class Solution {
public:
    /**
    * @param start, a string
    * @param end, a string
    * @param dict, a set of string
    * @return an integer
    */
    int ladderLength(string start, string end, unordered_set<string> &dict) {
        // write your code here
        if (start == end)
            return 1;
        if (start.size() != end.size())
            return 0;
        if (start.empty() || end.empty() || dict.empty())
            return 0;
        queue<string> path;
        path.push(start);
        map<string, int> count;
        count[start] = 1;
        dict.erase(start);
        while (!path.empty())
        {
            string str = path.front();
            path.pop();
            int n = count[str];
            for (int i = 0; i < str.size(); ++i)
            {
                string temp = str;
                for (char j = 'a'; j <= 'z'; ++j)
                {
                    if (temp[i] == j)
                        continue;
                    else
                        temp[i] = j;
                    if (dict.find(temp) != dict.end())
                    {
                        path.push(temp);
                        count[temp] = n + 1;
                        dict.erase(temp);
                    }
                    if (temp == end)
                        return n + 1;
                }
            }

        }
        return 0;
    }
};
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值