首页 > 其他 > 详细

字符串对点按段翻转

时间:2014-01-21 00:50:30      阅读:343      评论:0      收藏:0      [点我收藏+]

       最近浏览博客,遇到这样的题,于是就敲了敲,感激比较简单。

       请实现一个程序,能对点分字符串按段翻转。如”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;
}

     运行结果:

bubuko.com,布布扣

      有很多不合理的地方,欢迎斧正!

字符串对点按段翻转

原文:http://blog.csdn.net/xj2419174554/article/details/18360421

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!