解题思路

给定一个由字母、数字和空格组成的字符串,以及一个字符(不为空格),需要统计该字符在字符串中出现的次数,不区分大小写

  • 统一大小写: 为了在比较时不区分大小写,我们需要将输入的字符串和要查找的字符都转换为同一种大小写形式(通常转换为全小写或全大写)。
  • 字符统计: 遍历转换后的字符串,逐个字符与目标字符进行比较,如果相同,计数器加一。
  • 输入处理:
    • 字符串输入: 使用 getline 函数读取整行输入,确保读取包含空格的整个字符串。
    • 字符输入: 单独读取要查找的字符。

代码


#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string inputStr;
    char targetChar;

    // 读取包含空格的整行字符串
    std::getline(std::cin, inputStr);

    // 读取要查找的字符
    std::cin >> targetChar;

    // 将目标字符转换为小写
    targetChar = std::tolower(targetChar);

    // 初始化计数器
    int count = 0;

    // 遍历字符串,统计目标字符出现次数
    for (char c : inputStr) {
        if (std::tolower(c) == targetChar) {
            count++;
        }
    }

    // 输出结果
    std::cout << count << std::endl;

    return 0;
}
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // 读取包含空格的整行字符串
        String inputStr = sc.nextLine();

        // 读取要查找的字符
        String target = sc.nextLine();
        char targetChar = target.toLowerCase().charAt(0);

        int count = 0;

        // 遍历字符串,统计目标字符出现次数
        for (char c : inputStr.toCharArray()) {
            if (Character.toLowerCase(c) == targetChar) {
                count++;
            }
        }

        // 输出结果
        System.out.println(count);
    }
}
# 读取包含空格的整行字符串
input_str = input().strip()

# 读取要查找的字符
target_char = input().strip().lower()

# 初始化计数器
count = 0

# 遍历字符串,统计目标字符出现次数
for c in input_str:
    if c.lower() == target_char:
        count += 1

# 输出结果
print(count)

算法及复杂度

  • 时间复杂度:

    • 对于长度为 的输入字符串,遍历一遍字符串的时间复杂度为
    • 因此,算法的时间复杂度为
  • 空间复杂度:

    • 需要额外的空间存储输入的字符串和计数器,空间复杂度为
    • 由于只需要常数级别的额外空间(计数器和几个变量),因此空间复杂度为 ,其中 是字符串的长度。