中级农民
- 积分
- 119
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-3-11
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
https://leetcode.com/problems/word-ladder/
以下是我的解法, 然而用comment掉的那句for (int i=0; i<q.size(); i++) 结果就不对了, 用for (int size = q.size(); size > 0; size--) 就对, 我打印了一下计数值并没什么区别, 哪位大神能告诉我一下这是为什么呀。。。已经被整懵了... thanks!
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> dict(wordList.begin(), wordList.end());
if (!dict.count(endWord))
{
return 0;
}
queue<string> q;
q.push(beginWord);
int len=beginWord.length();
int step=0;
int count=0;
while (!q.empty())
{
step++;
//for (int i=0; i<q.size(); i++) //incorrect
for (int size = q.size(); size > 0; size--) //correct
{
string w=q.front();
q.pop();
count++;
cout<<"count:"<<count<<endl;
for (int j=0; j<len; j++)
{
char ch=w[j];
for (int k='a'; k<='z'; k++)
{
w[j]=k;
if (w==endWord)
{
return step+1;
}
if (!dict.count(w))
{
continue;
}
dict.erase(w);
q.push(w);
}
w[j]=ch;
}
}
} //end of while
return 0;
}
};
-------
input:
"hit"
"cog"
["hot","dot","dog","lot","log","cog"]
output:4
expected: 5
stdout:count:1
count:2
count:3
count:4
count:5
|
上一篇: 想问下可以用R语言刷LeetCode吗下一篇: lc崩了吗
|