字符串移动,还需要多写题

自己写的:超时
//在幼儿园有n个小朋友排列为一个队伍,从左到右一个挨着一个编号为(0~n - 1)。其中有一些是男生,有一些是女生,男生用'B'表示,女生用'G'表示。小朋友们都很顽皮,当一个男生挨着的是女生的时候就会发生矛盾。作为幼儿园的老师,你需要让男生挨着女生或者女生挨着男生的情况最少。你只能在原队形上进行调整,每次调整只能让相邻的两个小朋友交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整多少次可以让上述情况最少。例如:
//GGBBG->GGBGB->GGGBB
//这样就使之前的两处男女相邻变为一处相邻,需要调整队形2次
#include <cstdio>  
#include<iostream>
#include <queue>  
#include <vector>  
#include <functional>  
#include<string>
#include<cctype>
#include<map>
#include<algorithm>
using namespace std;  


int main()
{
string str;
cin >> str;
int count = 0;
int begin = 0, end = str.length()-1;
while (!(begin >= end))
{
while(str[begin] != 'B') begin++;
while (str[end] != 'G') end--;
if (begin > end) break;
count += end - begin;
begin++;
end--;
}
int count1 = 0;
begin = 0, end = str.length()-1;
while (!(begin >= end))
{
while (str[begin] != 'G') begin++;
while (str[end] != 'B') end--;
if (begin > end) break;
count1 += end - begin;
begin++;
end--;
}
cout <<(count<count1?count:count1);
return 0;
}



简短:


#include<iostream>
#include<string>
using namespace std;

int main(){
    string str;
    cin>>str;
    int bCount=0,gCount=0,b=0,g=0;
    for(int i=0;i<str.size();i++){
        if(str[i]=='B'){
            bCount+=i-b;
            b++;
        }
        else{
            gCount+=i-g;
            g++;
        }
    }
    cout<<min(bCount,gCount)<<endl;

    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值