【发布时间】:2020-08-26 16:38:16
【问题描述】:
#include <bits/stdc++.h>
using namespace std;
#include <unordered_set>
#include <queue>
struct word {
string s;
int level;
word(string a, int b)
: s(a)
, level(b)
{
}
};
bool isadj(string s1, string s2)
{
int len = s1.length(), count = 0;
for (int i = 0; i < len; i++) {
if (s1[i] != s2[i])
count++;
if (count > 1)
return false;
}
return count == 1 ? true : false;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string> st;
for (string s : wordList)
st.insert(s); // adding elements into a set
if (st.find(endWord) == st.end())
return 0;
queue<word> q;
q.push(word(beginWord, 0)); // initialising the queue
while (!q.empty()) {
word temp = q.front(); // pop the current string
q.pop();
if (temp.s == endWord)
return temp.level;
for (auto it = st.begin(); it != st.end(); it++) { // loop over the set to find strings at a distance of 1 and add them to the queue
if (isadj(temp.s, *it)) // i have inserted code here to print the string *it
{
q.push(word(*it, temp.level + 1));
st.erase(*it); // delete the element to avoid looping
}
}
}
return 0;
}
int main()
{
// make dictionary
vector<string> D;
D.push_back("poon");
D.push_back("plee");
D.push_back("same");
D.push_back("poie");
D.push_back("plie");
D.push_back("poin");
D.push_back("plea");
string start = "toon";
string target = "plea";
cout << "Length of shortest chain is: "
<< ladderLength(start, target, D);
return 0;
}
我要解决的问题是https://leetcode.com/problems/word-ladder/ 我无法追踪我在哪里使用了在我的程序中再次释放的内存?
以下是我的调试尝试:
我试图在另一个在线 ide 上运行它,代码编译并成功运行,但给出了错误的答案。为了调试它,我在我的代码中插入了一些行,以便打印当前字符串距离为 1 的所有字符串。令人惊讶的是,集合中出现了一个空字符串。请帮助我了解我在哪里做错了。
【问题讨论】:
-
您应该在本地配置一个 IDE 并在附加调试器的情况下运行它。仅使用在线工具进行开发是一种糟糕的方法。
-
您似乎在使用
include <bits/stdc++.h>却不知道它的实际作用。所以请阅读this 和Why is “using namespace std;” considered bad practice? -
可能不是当前的问题,但在
isadj中你默默地假设s2不长于s1,如果是你正在访问s2越界跨度> -
@idclev463035818 假设所有字符串的长度相同
-
绝对不是当前的问题:在许多地方,您正在制作不必要的副本。传递参数和
for (string s : wordList) st.insert(s);,如果我计算正确,字符串(例如"poon")在它们最终进入unordered_set 之前被复制3 次
标签: c++ breadth-first-search unordered-set