文章
454
粉丝
0
获赞
1
访问
10.4k
输入一行可能含连续空格的英文句子,把单词顺序整体反转输出,连续空格合并成一个。
按空格切词后逆序拼接即可;连续空格切出来的空串要跳过。
输入含空格甚至首尾空格,必须整行读入,不能用 cin>> 或 split() 之外的分词方式。
输出末尾不要留多余空格。
时间 O(L),空间 O(L)。
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...
登录后发布评论
暂无评论,来抢沙发