例3 一个字符串只包含*和数字,请把它的*号都放开头。
方法1:
快排partition——数字相对顺序会变化
循环不变式:[0..i – 1]都是*,[i..j– 1]是数字,[j..n– 1]未探测
程序如下:
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
class Solution {
public:
char* Repace(char A[]) {
int lenA = strlen(A);
int i = 0;
for(int j = 0;j < lenA; ++j)
{
if(A[j] == '*')
{
char temp = A[i];
A[i] = A[j];
A[j] = temp;
i++;
}
}
return A;
}
};
int main()
{
Solution* p = new Solution;
char B[100] = "*1*2*3";
//p->changeSpace(B);
cout <<p->Repace(B)<< endl;
delete p;
return 0;
}
方法2 :倒序,可保持数字位置相对不变
代码如下:
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
class Solution {
public:
char* daozhe(char A[])
{
int lenA = strlen(A);
int j = lenA - 1;
for(int i = lenA - 1; i >= 0;--i)
{
if(A[i] != '*')
A[j--] = A[i];
}
cout << j << endl;
for(int i = 0;i <= j;++i)
A[i] = '*';
return A;
}
};
int main()
{
Solution* p = new Solution;
char B[100] = "*1*2*3";
//p->changeSpace(B);
cout <<p->daozhe(B)<< endl;
delete p;
return 0;
}