word-ladder i

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 length5.

Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters.

用一个栈记录记过的元素,每次用栈顶元素和数组元素及end比较,进行处理,在vs中可以通过

用例   "hit","cog",["hot","cog","dot","dog","hit","lot","log"]

vs 输出为5,网上输出为3

class Solution {
public:
bool isnext(string s1, string s2)
{
int count = 0;

for (int i = 0, j = 0; i<s1.size(), j<s2.size(); i++, j++)
{
if (s1[i] != s2[j])
count++;
}
if (count == 1)
return true;
else
return false;
}
int ladderLength(string start, string end, unordered_set<string> &dict) {
int count = 1;
if (isnext(start, end) && dict.find(start) != dict.end() && dict.find(end) != dict.end())
return ++count;
stack<string> sk;
sk.push(start);
unordered_set<string> ::iterator it = dict.begin();

for (; it != dict.end(); it++)
{
if (isnext(sk.top(), *it))
{
sk.push(*it);
}
if (isnext(sk.top(), end))
{
break;
}
}
if(sk.size()<=1)
return 0;

return sk.size() + 1;
}
};

 

转载于:https://www.cnblogs.com/ranranblog/p/5627277.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值