题解 | #单词倒排#

方法一:单词原地逆序
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse(char* pa, char* pb)
{

	while (pa < pb)
	{
		char temp = *pa;
		*pa = *pb;
		*pb = temp;
		pa++;
		pb--;
	}
}
int main()
{
	char ch[10000] = { 0 };
	gets(ch);
	int x = 0, y = 0;
	int n = strlen(ch);
	for (int i = 0; i < n; i++)
	{
		if (isalpha(ch[i]))//寻找每个单词的首字母
		{
			x = i;//用x记录首字母位置
			y = i;//用y接收i,继而寻找该字母的尾字母的位置
			while (isalpha(ch[y]))
			{
				y++;
			}
			--y;//找到尾字母的位置
			reverse(&ch[x], &ch[y]);//对该单词进行逆置
			i = y;//将遍历因子的位置改为y的位置,下次遍历位置会从该尾字母后开始
		}
	}
	for (int i = n - 1; i >= 0; i--)//从后向前遍历,打印所有单词
	{
		if (isalpha(ch[i]))
		{
			printf("%c", ch[i]);
		}
		else
		{
			printf(" ");
		}
	}
	return 0;
}
方法二:直接打印
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
    char ch[1000] = { 0 };
    gets(ch);
    int i;
    for (i = strlen(ch) - 1; i >= 0; i--)
    {
        if (!isalpha(ch[i]))
        {
            printf("%s", &ch[i + 1]);
            ch[i] = '\0';//为下一次的打印创造条件
            printf(" ");
        }
    }
    printf("%s", ch);
    return 0;
}
该题库类似题目:HJ13--句子逆序
这是俺的题解链接🤔
全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务