数颜色
思路
这题有啥好想的?给你一个只含 R、G、B 三种字符的字符串,分别数一下各出现了几次,按 (R个数,G个数,B个数) 的格式输出就行。
怎么做?
- 读入字符串
- 遍历每个字符,碰到
R就 r++,碰到G就 g++,碰到B就 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++;
}
// 注意输出格式:(R,G,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++;
}
// 注意输出格式:(R,G,B)
System.out.println("(" + r + "," + g + "," + b + ")");
}
}
s = input()
r = s.count('R')
g = s.count('G')
b = s.count('B')
print(f"({r},{g},{b})")
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line));
rl.on('close', () => {
const s = lines[0].trim();
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})`);
});
复杂度
- 时间复杂度:
,遍历一遍字符串
- 空间复杂度:
,只用了三个计数变量
总结
签到题,没啥好说的。遍历一遍计数,格式化输出,搞定收工。



京公网安备 11010502036488号