У меня были проблемы с поиском ответа на этот вопрос. Я надеюсь, что это не дубликат. Я написал код для вызова leetcode.com, который работает в VS17, как и ожидалось, но не на leetcode или на моем Ubuntu WSL, скомпилированном с g ++. Код ищет самую длинную подстроку с уникальными буквами. Ответ для строки "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;
}
Редактировать: я добавил цикл итератора для печати значений в наборе после каждого инициала для выполнения цикла, и 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 в неправильном порядке?