一、字符串:
public class 重複元素計數 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("");
String str = sc.nextLine();
HashMap<Character, Integer> hashMap = new HashMap<>();
char[] chs = str.toCharArray();
for (char c : chs) {
if (hashMap.containsKey(c)) {
Integer num = hashMap.get(c);
num++;
hashMap.put(c, num);
}else {
hashMap.put(c, 1);
}
}
System.out.println(hashMap);
}
}
運行結果:
二、數組:
public class ArrayTest {
public static void main(String[] args) {
array();
}
public static void array(){
int[] arr = {4,5,3,4,6,2,3,4,5,8,6,7,5,8,4,3,2,4,5,6,7,5,4,3,5,6,7,5,4,};
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int m = arr[i];
if (map.containsKey(m)){
int num = map.get(arr[i]);
num++;
map.put(arr[i],num);
}else {
map.put(arr[i],1);
}
}
System.out.println(map);
}
}
打印結果: