题解 | #字符个数统计#
字符个数统计
https://www.nowcoder.com/practice/eb94f6a5b2ba49c6ac72d40b5ce95f50
题解
此题解决的方法有很多。
1.使用set的去重特性解决
import java.util.Scanner; import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); Set<Character> set = new HashSet<>(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); set.add(ch); } System.out.println(set.size()); } } }
2.使用String.contains()方法来排查重复
import java.util.Scanner; import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String str = sc.nextLine(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); // 如果在sb中没有则添加 if (!sb.toString().contains(ch + "")) { sb.append(ch); } } System.out.println(sb.length()); } } }
做题过程中犯的错误做法
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNextLine()) { String str = sc.nextLine(); int count = 0; while(str.length() > 0) { char ch = str.charAt(0); str = str.replaceAll(ch+"", ""); count++; } System.out.println(count); } } }
错误原因:当输入的用例为"uqic^g`(s&jnl(m#vt!onwdj(ru+os&wx"时,”^“为死循环,因为replaceAll()中接收的参数为正则表达式;因此在做题的使用应该多考虑此处的犯错。