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;
}
};

 

posted @ 2016-06-29 16:18  ranran1203  阅读(154)  评论(0编辑  收藏  举报