不同字符
[题目链接](https://www.nowcoder.com/practice/12abaf3aaa944c768f3e64444592f63a)
思路
题目很直白:给你一个只包含大小写字母和数字的字符串,问里面有多少种不同的字符。
"不同"两个字天然对应集合这个数据结构——把所有字符丢进集合里,重复的自动去掉,最后集合的大小就是答案。
拿示例 aase3 来验证:a 出现了两次,但集合里只留一个,加上 s、e、3,一共 4 种,符合预期。
代码
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
string s;
cin >> s;
set<char> st(s.begin(), s.end());
cout << st.size() << endl;
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
Set<Character> set = new HashSet<>();
for (char c : s.toCharArray()) {
set.add(c);
}
System.out.println(set.size());
}
}
n = int(input())
s = input()
print(len(set(s)))
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin });
const lines = [];
rl.on('line', line => lines.push(line));
rl.on('close', () => {
const s = lines[1];
console.log(new Set(s).size);
});
复杂度分析
- 时间复杂度:
,遍历一遍字符串即可。
- 空间复杂度:
,其中
是字符集大小。本题字符集为大小写字母加数字,最多 62 种,所以集合占用的空间是常数级别的。

京公网安备 11010502036488号