【发布时间】:2018-11-18 01:15:45
【问题描述】:
我很难找到答案。我希望它不是重复的。我为 leetcode.com 挑战编写了代码,该挑战在 VS17 中按预期工作,但不适用于 leetcode 或我用 g++ 编译的 Ubuntu WSL。该代码搜索具有唯一字母的最长子字符串。字符串“pwwkew”的答案是 3(VS17 得到 3),但在 Linux 和 leetcode 上却是 4。我猜这与 MinGW 与 G++ 有关。在 Ubuntu 上,我使用多个不同版本的 C++ 编译了该程序:g++ -Wall -Wextra -Werror string.cpp -std=c++1y -o string
提前致谢!这也是我的第一篇文章,所以请放轻松:)。
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
#include <set>
#include <unordered_set>
using namespace std;
/*
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
*/
int main()
{
string s = "pwwkew";
//this algorithm adds unique chars to a set in the order that they appear in the string
//after each for loop, the maximum number between maxLen and the size of the set is recorded
//when a duplicate letter is found, all of the letters up until and including the last
//occurence of that letter are erased, so the remaining letters are only the uniques in the current 'substring'
unordered_set<char> seen;
int maxLen = 0;
for (int end = 0; end < s.size(); end++)
{
if (seen.insert(s[end]).second == false)
{
if (seen.begin() == seen.find(s[end]))
{
seen.erase(seen.begin());
}
else {
seen.erase(seen.begin(), seen.find(s[end+1]));
}
seen.insert(s[end]);
}
maxLen = max(maxLen, (int)seen.size());
}
return 0;
}
编辑:我添加了一个迭代器循环以在每次初始 for 循环执行后打印集合中的值,VS17 打印:
p
p w
w
w k
w k e
k e w
Linux 打印时:
p
w p
w p
k p w
e k p w
w
所以我猜插入顺序被一个编译器颠倒了,这会导致我的 set.erase 以错误的顺序执行?
【问题讨论】:
标签: c++ linux visual-studio g++ mingw