首页 > 解决方案 > 打印带有一个错位字符串的字符串序列

问题描述

我正在做一个有趣的练习(不是家庭作业),给定一个排序的字符串序列,一个单词出现得太早,我们必须打印排序的序列。关键是我们必须用 O(1) 辅助空间来做,所以 novectorlist

我尝试了以下方法:

#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

标签: c++algorithm

解决方案


您可以将代码简化为:

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;

演示


推荐阅读