题解 | #字符个数统计#
字符个数统计
https://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50
解题思路
- 使用集合(Set)来存储不同的字符
- 遍历输入字符串的每个字符:
- 检查字符的ASCII码是否在0-127范围内
- 如果在范围内,则加入集合
- 最后输出集合的大小,即不同字符的个数
- 注意:
- 相同字符只计算一次
- 只统计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