【问题标题】:Print a sequence of strings with one missplaced string打印带有一个错位字符串的字符串序列
【发布时间】:2020-11-03 18:26:13
【问题描述】:

我正在做一个有趣的练习(不是家庭作业),给定一个排序的字符串序列,其中一个单词出现得太早,我们必须打印排序的序列。 关键是我们必须使用 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 个字符串:一个带有要处理的当前值,一个带有下一个字符串,一个带有放置错误的单词,称为 maltrobat 表示是否找到了未排序的单词但尚未打印。

如果单词放置正确,我们使用else if (current &lt; next) 打印它。 如果不是,我激活标志 trobat 并打印下一个值,因为必须对下一个值进行排序。 然后,对于第一个 if,如果我找到了值,我检查 mal 是否在正确的位置,否则我打印当前并重复该过程。

我在以下测试中遇到问题:

INP1:

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

INP2:

f
aaaaaa
bbbbb
cccc
ddd
ee
END

输出2:

aaaaaa
aaaaaa
bbbbb
cccc
ddd
f

预期 OUT2:

aaaaaa
bbbbb
cccc
ddd
ee
f

【问题讨论】:

  • 请注意,您将所有输入字符串附加到s。这绝对不是O(1) 空间,此时您不妨使用向量。此外,您需要显示程序的输出。
  • @cigien 在 OP 中写道,我仅将 s 用于调试目的。我将使用输出进行编辑。
  • 哦,原来如此。是的,在你得到的输出中编辑。
  • @cigien 我添加了s的值,因为终端同时显示输入和输出,一切都是一团糟......希望它有意义。
  • “终端同时显示输入和输出”。您可以使用所有输入创建文件,然后执行cat input.txt | my_app.exe。不会混合输入/输出。 (但不再是交互式的)。

标签: c++ algorithm


【解决方案1】:

您可以将代码简化为:

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;

Demo

【讨论】:

  • 干得漂亮!没想到这个……比一堆if的优雅多了
猜你喜欢
  • 2021-02-24
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 2017-11-23
相关资源
最近更新 更多