题目:如果一个字符串是由RGB三个字母随机组成的,那么试将所有的R移动到字符串的左端,B移动到右端,G在中间。
方法:本题跟将一个数组的奇数偶数分开,或者正数负数分开类似。起初可以将GB看成一种情况,讲R和GB分别放在左右两端,然后再将GB分开。
#include<iostream>
using namespace std;
int main()
{
char str[] = "RRRBGBGGGBBBRRRBGRB";
char *begin,*end;
begin = end = str;
cout<<str<<endl;
while(*begin == 'R' && *begin != '\0')
begin++;
if(*begin == '\0')
return 0;
end = begin;
while(*end != '\0')//下面代码是将R移动到字符串的左边,RB暂时不区分,都放在右边
{
if(*end == 'R')
{
char ch = *begin;
*begin = *end;
*end = ch;
begin++;
//end++;
}
end++;
}
//the code above used to move all R to the left side
--end;
cout<<str<<endl;
while(begin < end)//这里讲GB分开,B放在右边
{
if(*begin == 'G')
begin++;
if(*end == 'B')
end--;
if(*begin == 'B' && *end =='G' && begin<end)
{
char ch = *begin;
*begin = *end;
*end = ch;
begin++;
end--;
}
}
//the code above used to partion the G and B
cout<<str<<endl;
return 0;
}