题源 👉 字符个数统计_牛客题霸_牛客网 (nowcoder.com)
题目描述:
示例:
思路:
方法一:
ASCII码范围在0~127,范围较小,借助辅助数组空间Helper:
遍历字符串,令Helper[出现字符ASCII码]++,记录已出现字符
再遍历辅助数组Helper,若不为0即表示该下标所示字符出现过,进行计数。
方法二:
也可以使用Java的HashSet,遍历每个字符,添加到HashSet中(HashSet可以去重),最后输出HashSet的大小。
具体实现:
方法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int[] helper = new int[128];
int cnt = 0;
for(int i = 0; i < s.length(); i++)
helper[s.charAt(i)]++;
for(int i = 0; i < helper.length; i++)
if(helper[i] != 0) cnt++;
System.out.println(cnt);
}
}
方法二:
import java.util.Scanner;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
HashSet<Character> helper = new HashSet<>();
for(int i = 0; i < s.length(); i++)
helper.add(s.charAt(i));
System.out.println(helper.size());
}
}
时间复杂度:
都是O(n)