题目链接
题目描述
给定一个只包含大写字母 'R', 'G', 'B' 的字符串 ,代表一条彩虹的颜色序列。请统计这三种字母各出现了多少次,并按照
(R_count,G_count,B_count)
的格式输出结果。
解题思路
这是一个基础的字符计数问题。最直接的方法是遍历整个字符串,并为每种颜色维护一个计数器。
- 初始化三个整数变量
countR
,countG
,countB
为,分别用来记录 'R', 'G', 'B' 的数量。
- 从头到尾遍历输入的字符串
。
- 对于字符串中的每一个字符,进行判断:
- 如果字符是 'R',则将
countR
加一。 - 如果字符是 'G',则将
countG
加一。 - 如果字符是 'B',则将
countB
加一。
- 如果字符是 'R',则将
- 遍历结束后,三个计数器就分别存储了对应颜色的出现次数。
- 最后,按照指定的格式
(countR,countG,countB)
将结果输出。
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int countR = 0;
int countG = 0;
int countB = 0;
// 遍历字符串中的每个字符
for (char c : s) {
if (c == 'R') {
countR++;
} else if (c == 'G') {
countG++;
} else if (c == 'B') {
countB++;
}
}
// 按格式输出
cout << "(" << countR << "," << countG << "," << countB << ")" << '\n';
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 countR = 0;
int countG = 0;
int countB = 0;
// 遍历字符串中的每个字符
for (char c : s.toCharArray()) {
if (c == 'R') {
countR++;
} else if (c == 'G') {
countG++;
} else if (c == 'B') {
countB++;
}
}
// 按格式输出
System.out.println("(" + countR + "," + countG + "," + countB + ")");
}
}
# 读取输入字符串
s = input()
# 使用字符串内置的count方法直接计数
count_r = s.count('R')
count_g = s.count('G')
count_b = s.count('B')
# 使用f-string按格式输出
print(f"({count_r},{count_g},{count_b})")
算法及复杂度
- 算法:线性扫描/单次遍历。
- 时间复杂度:我们需要遍历一次长度为
的字符串来统计字符。因此,时间复杂度为
,其中
是字符串
的长度。
- 空间复杂度:我们只使用了三个额外的整数变量来存储计数结果,这与输入字符串的长度无关。因此,空间复杂度为
。