我正在做一个有趣的练习(不是家庭作业),给定一系列字符串排序,一个单词出现太早,我们必须打印排序后的序列。关键是我们必须使用O(1)辅助空间来做,所以vector
既不list
我尝试了以下方法:
#include <iostream>
#include <string>
using namespace std;
int main() {
string current, next, mal;
bool trobat = false;
cin >> current >> next;
while (next != "END") {
if (trobat) {
if (mal > current and mal < next) {
cout << current << endl;
cout << mal << endl;
trobat = false;
}
else {
cout << current << endl;
}
}
else if (current < next) {
cout << current << endl;
}
else {
trobat = true;
mal = current;
cout << next << endl;
}
current = next;
cin >> next;
}
if (trobat) {
cout << mal << endl;
}
else {
cout << current << endl;
}
}
基本上,我尝试使用3个字符串:一个带有要处理的当前值,一个带有下一个,以及一个带有错误放置的词(称为)mal
。trobat
指示是否找到但未打印未排序的单词。
如果正确放置了单词,我们将使用进行打印else if (current < next)
。如果不是,我将激活trobat标志并打印下一个值,因为下一个必须进行排序。然后,对于第一个(如果找到)该值,则检查是否mal
在正确的位置,否则将打印当前值并重复该过程。
我在进行以下测试时遇到了麻烦:
INP1:
a
b
e
c
d
f
g
END
OUT1:
a
b
c
c
d
e
f
g
预期的OUT1:
a
b
c
d
e
f
g
INP2:
f
aaaaaa
bbbbb
cccc
ddd
ee
END
OUT2:
aaaaaa
aaaaaa
bbbbb
cccc
ddd
f
预期的OUT2:
aaaaaa
bbbbb
cccc
ddd
ee
f
您可以将代码简化为:
std::string word1;
std::string word2;
std::cin >> word1 >> word2;
while (word2 != "END") {
std::cout << std::min(word1, word2) << std::endl;
word1 = std::max(word1, word2);
std::cin >> word2;
}
std::cout << word1 << std::endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句