将一个包含星号的字符串中所有星号位置提前,其他字符保持相对位置不变
时间O(n),空间O(1)
后向前遍历遇到非星号的就与最后一个星号位置交换
交换次数为最后一个星号之前的非星号字符个数,稍微想一想就懂了
交换的额外空间为零 +_+ 直接位运算交换
因为相比遍历,交换是很浪费时间的
如果字符串长度已知只需要遍历一遍,如果未知则需要遍历两遍。
空间方面申请2个计数的临时变量可以了
注: 最快的方法肯定是直接指针移动了,不过思路就这个了,有兴趣自己改吧。
主要心思应该还是放在关注在解法的思路上。一些细枝末节的优化啥的也没个啥意思。
直接上代码了
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int MAXN = 100;
char str[MAXN];
int main()
{
while(scanf("%s",str)!=EOF)
{
int la = strlen(str)-1;
while(str[la] != '*' && la>=0)la--;
for(int i = la-1;i>=0;i--)
if(str[i]!='*')
str[i]^=(str[la--]^=(str[i]^=str[la]));
printf("%s\n",str);
}
}