假设我们需要计算并打印给定字符串中每个字符的出现次数。为简单起见,该字符串仅由小写字母组成。我编写了以下两个函数,并想知道哪个在Java中更有效/更可取。
函数1:
private void countAndPrintArray1(String str){
int[] a = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = c - 'a';
a[index] = a[index] + 1;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = a[c -'a'];
System.out.println(c+" -> "+ freq);
}
}
功能2:
private void countAndPrintArray2(String str){
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.getOrDefault(c, 0) + 1;
map.put(c, freq);
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.get(c);
System.out.println(c+" -> "+ freq);
}
}