字符串字符频率计算代码核心计数逻辑的疑问求助
Hey there! Let's break down that confusing line step by step—it's actually a clever trick using character encoding to make frequency counting super efficient, and it's easier to grasp than it looks.
1. How str.charAt(i) - 'a' Maps Characters to Array Indices
In Java, every char is secretly an integer under the hood, corresponding to its Unicode value (for lowercase English letters, this matches ASCII values perfectly).
- The character
'a'has a Unicode value of 97,'b'is 98, all the way up to'z'which is 122. These values are consecutive—no gaps between them. - When you subtract
'a'from another lowercase letter, you convert it to a 0-25 index:'a' - 'a' = 0→ maps tofreq[0]'b' - 'a' = 1→ maps tofreq[1]- ...
'z' - 'a' = 25→ maps tofreq[25]
This turns each lowercase letter into a unique index in the freq array—essentially using the array as a tiny, fast hash table (no fancy hash calculations needed!). The SIZE constant here should definitely be set to 26 to cover all 26 lowercase letters.
2. How freq[str.charAt(i) - 'a']++ Tracks Frequencies
The ++ part is straightforward once you get the index mapping:
- We loop through every character in the string
- Convert the character to its corresponding array index
- Increment the value at that index by 1
Let's use a quick example with the string "abac":
- First character
'a'→ index 0 →freq[0]becomes 1 - Second character
'b'→ index 1 →freq[1]becomes 1 - Third character
'a'→ index 0 →freq[0]jumps to 2 - Fourth character
'c'→ index 2 →freq[2]becomes 1
By the end of the loop, each position in freq holds the number of times its corresponding letter appeared in the string.
3. A Quick Heads Up About Edge Cases
One important thing to note: this code only works for lowercase English letters. If your string has uppercase letters, numbers, or symbols, str.charAt(i) - 'a' will give you a negative number or a value greater than 25, which will cause an ArrayIndexOutOfBoundsException. For broader character support, you'd want to use a HashMap<Character, Integer> instead.
内容的提问来源于stack exchange,提问作者abhigyan nayak

