RGB序列

题目:如果一个字符串是由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;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值