1009 说反话 (20 分)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello
本题我试了N种方案,都是只能通过两个测试点,其他两个测试点通不过……无奈……有大佬知道了麻烦指导下,万分感谢!
//这是我其中一种方案的代码;从后往前遍历,遇到空格则打印的思路
#include <cstdio>
#include <cstring>
int main()
{
char str[100];
scanf("%s", str);
int len = strlen(str);
for (int i = len; i >= 0; i--)
{
if (str[i] == ' ')
{
int j;
for (j = i+1; j < len && str[j] != ' '; j++)
{
printf("%c", str[j]);
}
if(j>i+1) printf(" ");
}
else if (i == 0)
{
for (int j = 0; j < len && str[j] != ' '; j++)
{
printf("%c", str[j]);
}
}
}
return 0;
}
//双栈思路;还有其他一些方案,不贴了,都是有两个测试点通不过55555555
#include <cstdio>
#include <cstring>
int main()
{
char str[100];
gets(str);
int len = strlen(str);
char stack1[100];
int top1 = -1;
for (int i = 0, flag=0; i < len; i++)
{
if (!flag && str[i] != ' ') flag = 1;
if (flag) stack1[++top1] = str[i];
}
while (top1 >= 0)
{
char stack2[80];
int top2 = -1;
while (top1 >= 0 && stack1[top1] != ' ')
{
stack2[++top2] = stack1[top1--];
}
while (top2 >= 0)
{
printf("%c", stack2[top2--]);
}
if(top1 >= 0) printf(" ");
while(stack1[top1] == ' ') top1--;
}
return 0;
}