import java.util.Scanner;
/**
* 在幼儿园有n个小朋友排列为一个队伍,从左到右一个挨着一个编号为(0~n-1)。其中有一些是男生,有一些是女生,男生用'B'表示,女生用'G'表示。
* 小朋友们都很顽皮,当一个男生挨着的是女生的时候就会发生矛盾。作为幼儿园的老师,你需要让男生挨着女生或者女生挨着男生的情况最少。你只能在原队形上进行调整,
* 每次调整只能让相邻的两个小朋友交换位置,现在需要尽快完成队伍调整,你需要计算出最少需要调整多少次可以让上述情况最少.例如: GGBBG -> GGBGB
* -> GGGBB 这样就使之前的两处男女相邻变为一处相邻,需要调整队形2次
*
* @author pomay
*
*/
public class Wangyi_movesite
{
public int movesite(String str)
{
char[] Bchild = str.toCharArray();
char[] Gchild = str.toCharArray();
int Bcount = 0;
int Gcount = 0;
char temp = ' ';
// B在前
// 趟数
for (int i = 0; i < Bchild.length; i++)
{
// 比较次数
for (int j = 0; j < Bchild.length - 1 - i; j++)
{
if (Bchild[j] == 'G' && Bchild[j + 1] == 'B')
{
temp = Bchild[j];
Bchild[j] = Bchild[j + 1];
Bchild[j + 1] = temp;
Bcount++;
}
}
}
// G在前
for (int i = 0; i < Gchild.length; i++)
{
// 比较次数
for (int j = 0; j < Gchild.length - 1 - i; j++)
{
if (Gchild[j] == 'B' && Gchild[j + 1] == 'G')
{
temp = Gchild[j];
Gchild[j] = Gchild[j + 1];
Gchild[j + 1] = temp;
Gcount++;
}
}
}
// System.out.println("Bcount" + Bcount);
// System.out.println("Gcount" + Gcount);
return Bcount <= Gcount ? Bcount : Gcount;
}
public static void main(String[] args)
{
// 输入数据包括一个长度为n且只包含G和B的字符串.n不超过50.
Scanner s = new Scanner(System.in);
String str = s.next();
Wangyi_movesite move = new Wangyi_movesite();
// 输出一个整数,表示最少需要的调整队伍的次数
System.out.println(move.movesite(str));
}
}
网易之幼儿园小朋友调整队形
最新推荐文章于 2017-11-24 18:23:18 发布