解题思路

  1. 使用集合(Set)来存储不同的字符
  2. 遍历输入字符串的每个字符:
    • 检查字符的ASCII码是否在0-127范围内
    • 如果在范围内,则加入集合
  3. 最后输出集合的大小,即不同字符的个数
  4. 注意:
    • 相同字符只计算一次
    • 只统计ASCII码在0-127范围内的字符

代码

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

int main() {
    string str;
    getline(cin, str);
    
    set<char> chars;
    for(char c : str) {
        if((unsigned char)c <= 127) {  // 检查ASCII范围
            chars.insert(c);
        }
    }
    
    cout << chars.size() << endl;
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        
        HashSet<Character> chars = new HashSet<>();
        for(char c : str.toCharArray()) {
            if(c <= 127) {  // 检查ASCII范围
                chars.add(c);
            }
        }
        
        System.out.println(chars.size());
    }
}
s = input()
chars = set()

for c in s:
    # ord()函数返回字符的ASCII值
    if ord(c) <= 127:
        chars.add(c)

print(len(chars))

算法及复杂度

  • 算法:使用集合进行字符去重统计
  • 时间复杂度: - 其中n为字符串长度
  • 空间复杂度: - k为不同字符的数量,最大为128