c++ - 打印带有一个错位字符串的字符串序列
问题描述
我正在做一个有趣的练习(不是家庭作业),给定一个排序的字符串序列,一个单词出现得太早,我们必须打印排序的序列。关键是我们必须用 O(1) 辅助空间来做,所以 novector
也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 并打印下一个值,因为必须对下一个值进行排序。然后,对于第一个 if,如果我找到了值,我检查是否mal
在正确的位置,否则我打印当前并重复该过程。
我在以下测试中遇到问题:
输入1:
a
b
e
c
d
f
g
END
输出1:
a
b
c
c
d
e
f
g
预期 OUT1:
a
b
c
d
e
f
g
输入法2:
f
aaaaaa
bbbbb
cccc
ddd
ee
END
输出2:
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;
推荐阅读
- javascript - 在javascript中制作一个魔方
- nrules - 为什么 IContext.RetractLinked 需要两个参数?
- awk - 使用 AWK,如何将十进制数转换为十六进制
- android - 在 Jetpack Compose 中的 API 响应后更新 LazyColumn
- amazon-web-services - 云平台和普通网站的真正区别是什么?
- c# - SqlBulkCopy WriteToServer 使用 IDataReader 而不是 DataTable 和以编程方式调整的字段值
- node.js - 在节点js中读取查询url参数
- sql - 使用自动生成的主键而不是常量唯一名称的好处
- python - 使用python将由逗号分隔的数据组成的文本文件转换为excel文件
- python - 如何在 Python 中使用自己的输出来提供 for 循环?