最近浏览博客,遇到这样的题,于是就敲了敲,感激比较简单。
请实现一个程序,能对点分字符串按段翻转。如”www taobao com”翻转为”com taobao www”,”sports sina com cn”翻转为
”cn com sina sports”。要求时间复杂度为O(n),空间复杂度为O(1),结果保存在参数指针所指的空间中。
本题要使单词顺序颠倒,但本身不变,难点在于时间复杂度为O(n),空间复杂度为O(1),这就说明直接模拟或开数组不适用。容易想到首先翻转整个字符串,然后以单词为单位翻转。
www taobao com
moc oaboat www
com taobao www
直接贴个代码吧!
#include<iostream>
#include<cstring>
using namespace std;
const int MAXN=200;
void solve(char *str)
{
int len=strlen(str);
printf("%s\n",str);
int i,mid=(len+0)>>1;
char ch;
for(i=0;i<mid;i++)
{
ch=str[i];
str[i]=str[len-1-i];
str[len-1-i]=ch;
}
printf("%s\n",str);
int j=0;
for(i=0;i<len;i++)
{
if(32==str[i])
{
int l=j,r=i-1;
while(l<r)
{
ch=str[l];
str[l]=str[r];
str[r]=ch;
l++,r--;
}
j=i+1;
}
}
printf("%s\n",str);
}
int main()
{
char str[MAXN];
while(gets(str))
{
if(strcmp(str,"END")==0)
break;
solve(str);
printf("\n");
}
return 0;
}
运行结果:
有很多不合理的地方,欢迎斧正!