文章

454

粉丝

0

获赞

1

访问

10.4k

头像
句子正序 题解(四语言 AC 代码)
P1004 兰州大学机试题题
发布于 2026年11月
阅读数 15

题意

输入一行可能含连续空格的英文句子,把单词顺序整体反转输出,连续空格合并成一个。

思路

  • 按空格切词后逆序拼接即可;连续空格切出来的空串要跳过。

  • 输入含空格甚至首尾空格,必须整行读入,不能用 cin>> 或 split() 之外的分词方式。

  • 输出末尾不要留多余空格。

复杂度

时间 O(L),空间 O(L)。

参考代码(C / C++ / Java / Python)

C:

#include <stdio.h>
#include <string.h>

static char line[1000005];
static char *w[200005];

int main(void)
{
    while (fgets(line, sizeof(line), stdin)) {
        int cnt = 0, i;
        char *p = strtok(line, " \t\r\n");
        while (p) {
            w[cnt++] = p;
            p = strtok(NULL, " \t\r\n");
        }
        for (i = cnt - 1; i >= 0; i--) {
            fputs(w[i], stdout);
            if (i) putchar(' ');
        }
        putchar('\n');
    }
    return 0;
}

C++:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

int main()
{
    string line;
    while (getline(cin, line)) {
        istringstream iss(line);
        vector<string> w;
        string s;
        while (iss >> s) w.push...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发