先上一下自己写的代码,自己测试样例是对的,但上传测试就。。。。
/**
* 说反话-加强版 (20 分)
给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过500 000的字符串。
字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用若干个空格分开。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子,并且保证单词间只有1个空格。
输入样例:
Hello World Here I Come
结尾无空行
输出样例:
Come I Here World Hello
结尾无空行
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 500000
#define STR_LEN 10
int main(int argc, char const *argv[])
{
char c;
char word[STR_LEN];
char *str_arr[MAX];
int word_count = 0;
int str_index = -1;
while (c = getchar())
{
// 是字母就加入
if (isalpha(c))
{
word[word_count++] = c;
}
// 遇到空格且单词长度不为0
else if (c == ' ' && !(strlen(word) == 0))
{
word[word_count] = '\0';
// 申请内存存放
char *ptr = (char *)malloc(sizeof(char) * strlen(word));
strcpy(ptr, word);
str_arr[++str_index] = ptr;
// 单词清空
word[0] = '\0';
word_count = 0;
}
else if (c == '\n' && !(strlen(word) == 0))
{
word[word_count] = '\0';
// 申请内存存放
char *ptr = (char *)malloc(sizeof(char) * strlen(word));
strcpy(ptr, word);
str_arr[++str_index] = ptr;
// 单词清空
word[0] = '\0';
word_count = 0;
break;
}
}
printf("%s", str_arr[str_index]);
for (int i = str_index - 1; i >= 0; i--)
{
printf(" %s", str_arr[i]);
}
return 0;
}
运行结果:
这是网上别人写的代码,加了点注释
原博客地址:https://blog.youkuaiyun.com/yubai258/article/details/81385188
#include <stdio.h>
#include <string.h>
int main()
{
/* 对输入字符串由后向前遍历,遇到空格就输出空格后的单词 */
char a[500001];
int l;
int i, j;
// 单个单词的长度
int word = 0;
// 标记是否是第一个单词
int first = 1;
gets(a);
l = strlen(a);
for (i = l - 1; i >= 0; i--)
{
if (word != 0 && a[i] == ' ')
{
// 是第一个单词
if (first == 1)
first = 0;
else
printf(" ");
// 输出空格后的word个字符
for (j = i + 1; j <= i + word; j++)
printf("%c", a[j]);
// 单词长度置0
word = 0;
}
else if (a[i] != ' ')
word++;
}
// 原来的第一个单词
if (word > 0)
{
if (first == 0)
printf(" ");
for (j = 0; j <= word - 1; j++)
printf("%c", a[j]);
}
return 0;
}