2014-04-09 单词内部翻转,顺序不变(谷歌面试题)

题目:

一个字符串,压缩其中的连续空格为1个后,对其中的每个字串逆序打印出来。比如"abc   efg  hij"打印为"cba gfe jih"。


思想:

这样的一个字符串,我们肯定涉及到一行遍历,关键我们在遍历到空格时应做控制,即逆序输出前面的子串,我想设立两个索引,first,end。起始遍历时,first和end分别指向首字母,然后便利时,只移动end到空格处停下。此时用temp保存好end的下一个索引。end向后回溯一个索引,此时first和end分别指要逆序的字串的开始与结束,此时我们只需要对调两个值即可,并向在中间回溯。进而first和end指向新的temp,进行新的一次交换直至结束。

其实该思想遍历了字符串两次,故时间复杂度为O(n);用到仅有的几个变量,故时间复杂度为O(1)。




程序实现:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void swap(char *first, char *end)
{
	char c;
	while(first <= end){
		c = *first;
		*first++ = *end;
		*end-- = c;
	}
}

int main(void)
{
	char string[256];	
	gets(string);
	char *first = string, *end = string, *temp;
	//printf("%d, %d\n", strlen(string), sizeof(string));

	while(end && *end != '\0'){
		if(*end == ' '){
			temp = end;
			temp++;
			swap(first, --end);
			first = temp;
			end = temp;
		}else{
			end++;
		}
	}
	swap(first, --end);	//last, we should ignore

	printf("%s", string);
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值