首页 > 试题广场 >

数颜色

[编程题]数颜色
  • 热度指数:1647 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}给定一个只包含 ``\texttt{R}``、``\texttt{G}``、``\texttt{B}`` 的字符串 S(代表一条彩虹的颜色序列),统计并``\text{(R,G,B)}`` 形式输出三种字母各出现多少次。

输入描述:
\hspace{15pt}一行输入字符串 S\ (1\leqq|S|\leqq10^5),仅含大写字母 ``\texttt{R}``、``\texttt{G}``、``\texttt{B}`` 


输出描述:
\hspace{15pt}按 ``\text{(R,G,B)}`` 形式输出计数结果,分别表示三种字符 ``\texttt{R}``、``\texttt{G}``、``\texttt{B}`` 各自的出现次数。
示例1

输入

RRGBBRG

输出

(3,2,2)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String rainbow = in.nextLine();

        int countR = 0;
        int countG = 0;
        int countB = 0;
        for (char c : rainbow.toCharArray()) {
            if (c == 'R') countR++;
            else if (c == 'G') countG++;
            else if (c == 'B') countB++;
        }
        System.out.print("(" + countR + ',' + countG + ',' + countB + ")");
    }
}

发表于 2025-08-28 16:34:34 回复(0)