解法一:遍历字符串

我们可以使用一个循环遍历字符串 $s$,并在遍历过程中统计数字字符、小写字母和大写字母的个数。

具体步骤如下:

  1. 初始化三个变量 digit_countlower_countupper_count,分别用来统计数字字符、小写字母和大写字母的个数,初始值都为 $0$。
  2. 遍历字符串 $s$ 的每一个字符:
    • 如果当前字符是数字字符,则将 digit_count 加 $1$。
    • 如果当前字符是小写字母,则将 lower_count 加 $1$。
    • 如果当前字符是大写字母,则将 upper_count 加 $1$。
  3. 输出 digit_countlower_countupper_count

下面是使用 Python 语言实现的代码:

s = input()

digit_count = 0
lower_count = 0
upper_count = 0

for c in s:
    if c.isdigit():
        digit_count += 1
    elif c.islower():
        lower_count += 1
    elif c.isupper():
        upper_count += 1

print(digit_count, lower_count, upper_count)

解法二:使用内置函数统计字符个数

除了手动遍历字符串统计字符个数外,我们还可以使用 Python 的内置函数 count 来直接统计数字字符、小写字母和大写字母的个数。

具体步骤如下:

  1. 初始化三个变量 digit_countlower_countupper_count,分别用来统计数字字符、小写字母和大写字母的个数,初始值都为 $0$。
  2. 使用 count 函数统计数字字符的个数,将结果赋值给 digit_count
  3. 使用 count 函数统计小写字母的个数,将结果赋值给 lower_count
  4. 使用 count 函数统计大写字母的个数,将结果赋值给 upper_count
  5. 输出 digit_countlower_countupper_count

下面是使用 Python 语言实现的代码:

s = input()

digit_count = s.count('0123456789')
lower_count = s.count('abcdefghijklmnopqrstuvwxyz')
upper_count = s.count('ABCDEFGHIJKLMNOPQRSTUVWXYZ')

print(digit_count, lower_count, upper_count)

复杂度分析

无论是解法一还是解法二,都需要遍历一次字符串 $s$,时间复杂度都为 $O(8)=O(1)$。

解法一使用了三个变量来统计字符个数,空间复杂度为 $O(1)$。

解法二使用了三个变量来存储统计结果,空间复杂度也为 $O(1)$

# yLOI2022 签到题## 题目描述给定一个长度为 $8$ 的字符串 $s$请你分别统计 $s$ 中大小写字母和数字字符的个数。## 输入格式输入只有一行一个长度为 $8$ 的字符串 $s$。## 输出格式输出一行三个整数依次表示:- $s$ 中数字字符的个数。- $s$ 中小写字母的个数。- $s$ 中大写字母的个数。## 样例 #1### 样例输入 #1yLOI2022### 样例输出

原文地址: http://www.cveoy.top/t/topic/ifHW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录