首页 > 解决方案 > 我们如何计算字符串中字符的频率

问题描述

我正在研究问题的解决方案。

    static void printCharWithFreq(String str) 
{ 
     // size of the string 'str' 
    int n = str.length(); 

    // 'freq[]' implemented as hash table 
    int[] freq = new int[SIZE]; 

    // accumulate freqeuncy of each character 
    // in 'str' 
    for (int i = 0; i < n; i++) 
        freq[str.charAt(i) - 'a']++; 

    // traverse 'str' from left to right 
    for (int i = 0; i < n; i++) { 

        // if frequency of character str.charAt(i) 
        // is not equal to 0 
        if (freq[str.charAt(i) - 'a'] != 0) { 

            // print the character along with its 
            // frequency 
            System.out.print(str.charAt(i)); 
            System.out.print(freq[str.charAt(i) - 'a'] + " ");  

            // update frequency of str.charAt(i) to  
            // 0 so that the same character is not 
            // printed again 
            freq[str.charAt(i) - 'a'] = 0; 
        } 
    } 
} 

我无法理解如何

for (int i = 0; i < n; i++) 
        freq[str.charAt(i) - 'a']++; 

能够计算元素的频率。以及如何将其存储回该位置。

我对此感到困惑。任何人都可以帮我吗?

标签: javaarraysstringdata-structures

解决方案


小写 ASCII 字母占据ASCII 表的连续部分,从索引 97 到 122。如果您的输入由小写 ASCII 字母组成,则表达式str.charAt(i) - 'a'将计算为范围[0, 25]中的值。a将变为0,b将变为1,c将变为2,依此类推。

然而,这种方法对于非小写 ASCII 字符会失败,例如,大写“A”字母的值为 65,因此'A' - 'a'65 - 97尝试访问负数组索引。


推荐阅读