题解 | #字符个数统计#
字符个数统计
https://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
Set<Character> set = new HashSet<>();
for (char c : in.toCharArray()) {
set.add(c);
}
System.out.println(set.size());
}
}
- Set<Character> set = new HashSet<>():创建一个 HashSet 集合,用于存储不同的字符。HashSet 是一个不允许重复元素的集合,这将确保在集合中存储的字符是唯一的。
- for (char c : in.toCharArray()):使用增强的for循环,遍历输入字符串的每个字符。in.toCharArray() 方法将字符串转换为字符数组,以便更容易遍历。
- set.add(c):在循环中,将当前字符 c 添加到 set 集合中。如果添加成功(即这是一个新字符),则说明该字符不重复。
set.size()返回集合中不同元素的数量
查看8道真题和解析
