题目:
一个字符串,压缩其中的连续空格为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;
}