彩色瓷砖

题目描述:

链接:https://www.nowcoder.com/questionTerminal/31af498841fd491886b8dee6ebde9768
来源:牛客网

牛牛喜欢彩色的东西,尤其是彩色的瓷砖。牛牛的房间内铺有L块正方形瓷砖。每块砖的颜色有四种可能:红、绿、蓝、黄。给定一个字符串S, 如果S的第i个字符是’R’, ‘G’, ‘B’或’Y’,那么第i块瓷砖的颜色就分别是红、绿、蓝或者黄。
牛牛决定换掉一些瓷砖的颜色,使得相邻两块瓷砖的颜色均不相同。请帮牛牛计算他最少需要换掉的瓷砖数量。

输入描述:

输入包括一行,一个字符串S,字符串长度length(1 ≤ length ≤ 10),字符串中每个字符串都是’R’, ‘G’, ‘B’或者’Y’。

输出描述:

输出一个整数,表示牛牛最少需要换掉的瓷砖数量

代码实现

import java.util.Scanner;

/**
 * Created by Cser_W on 2017/10/12.
 */

public class niuniuLikeColors {
    public static int countReplaceColors (String str) {
        if (str == null)
            return 0;
        int count = 0;
        char[] color = new char[]{'R','G','B','Y'};
        char[] colorArr = str.toCharArray();
        for (int i = 0; i < colorArr.length - 1; i++) {
            if (colorArr[i] == colorArr[i+1]) {
                if (i + 2 < colorArr.length) {
                    for (int j = 0; j < color.length; j++) {
                        if (colorArr[i] != color[j] && colorArr[i + 2] != color[j]) {
                            colorArr[i + 1] = color[j];
                            break;
                        }
                    }
                }
                i++;
                count ++;
            }
        }
        return count;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int res = countReplaceColors(str);
        System.out.println(res);
    }
}

猜你喜欢

转载自blog.csdn.net/u013310517/article/details/78220438