字符个数统计HashSet String Character
字符个数统计
https://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50
思路
去重首先想到用HashSet的add()方法,思路就是输入字符串→把字符串填入HashSet→输出size
刚开始没想着对输入的字符做限制,于是提交了两个版本,一个是对输入无判断的,二是判断输入的字符是否是字母。
v1:对输入无判断
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
//set.add
String str = in.next();
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < str.length(); i++) { //对字符串中的字符逐一添加
set.add(str.charAt(i));
}
System.out.println(set.size());
}
}
v2:判断输入的字符是否是字母
public class Main {
public static boolean isAsc(String str) {
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') {
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.next();
if (isAsc(str)) {
HashSet<Character> set = new HashSet<>();
for (int j = 0; j < str.length(); j++) {
set.add(str.charAt(j));
}
System.out.println(set.size());
} else {
System.out.println("错误输入");
}
}
}
}
总结
总体还算简单,字符串 String 的 charAt(位置) 方法学到了,可以对于字符串中指定位置的字符进行操作。
李咸鱼刷题小结 文章被收录于专栏
总结一下我的刷题过程、错误以及学到的知识