自己试着优化很多次了,但还是不行。
#include <stdio.h>
#include <string.h>
int main()
{
char a[200], temp[200] = {'\0'}, *p;
int count = 0, rcount = 0, x;
gets(a);
p = &a[0];
for (int i = strlen(a) - 1; i > 0; i--)
{
if (*(p + i) == ' '&&count == 0 && rcount == 1)
{
count++;
*(p + i) = '\0';
strcat(temp, p + i + 1);
strcat(temp, " ");
}
else if(*(p + i) == ' ')
{
count++;
*(p + i) = '\0';
}
else if (*p + i != ' ')
{
rcount = 1;
count = 0;
}
}
strcat(temp, a);
while (temp[strlen(temp) - 1] == ' ')
temp[strlen(temp) - 1] = '\0';
puts(temp);
return 0;
}
我猜是strcat方法的锅。这个方法应该会涉及到内存Copy,以及数组中某个字符是否为\0的判断,所以理论上讲调用一次会对数组进行2次遍历检查(temp查一次,p+i+1或a查一次),无形之中增加了时间。
我觉得不拼成字符串,直接做char的输出,可能会快一点。
你这逻辑这么写的这么复杂,还有两个循环,直接倒着来找单词,找到一个输出一次就行了