数颜色

[题目链接](https://www.nowcoder.com/practice/6beedfe2ba2740c99028737417eac01c)

思路

这道题非常直观——给你一个只由 RGB 三种字符组成的字符串,分别统计每种字符出现的次数,然后按 (R的次数,G的次数,B的次数) 的格式输出。

怎么做呢?遍历一遍字符串就行了:

  1. 初始化三个计数器 rgb,都设为 0。
  2. 逐个扫描字符串中的每个字符,遇到 'R' 就给 r 加一,遇到 'G' 就给 g 加一,遇到 'B' 就给 b 加一。
  3. 最后按要求的格式拼接输出即可。

注意输出格式是 (r,g,b),括号和逗号之间没有空格

代码

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

int main() {
    string s;
    cin >> s;
    int r = 0, g = 0, b = 0;
    for (char c : s) {
        if (c == 'R') r++;
        else if (c == 'G') g++;
        else if (c == 'B') b++;
    }
    cout << "(" << r << "," << g << "," << b << ")" << endl;
    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        int r = 0, g = 0, b = 0;
        for (char c : s.toCharArray()) {
            if (c == 'R') r++;
            else if (c == 'G') g++;
            else if (c == 'B') b++;
        }
        System.out.println("(" + r + "," + g + "," + b + ")");
    }
}
s = input()
print(f"({s.count('R')},{s.count('G')},{s.count('B')})")
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
rl.on('line', (s) => {
    let r = 0, g = 0, b = 0;
    for (const c of s) {
        if (c === 'R') r++;
        else if (c === 'G') g++;
        else if (c === 'B') b++;
    }
    console.log(`(${r},${g},${b})`);
    rl.close();
});

复杂度分析

  • 时间复杂度,其中 是字符串长度,只需遍历一次。
  • 空间复杂度,只用了三个计数变量。