我们如何计算字符串中字符的频率

时间:2019-02-27 14:16:30

标签: java arrays string data-structures

我正在寻找问题的解决方案。

    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']++; 

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

我对此感到困惑。 有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

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

但是,对于非小写ASCII字符(例如,大写字母“ A”的值为65,'A' - 'a'将为65 - 97,因此尝试访问负数组索引。

答案 1 :(得分:0)

在我看来,您可以用更简单的方式重写您的解决方案。除非我误会了,否则该解决方案的复杂程度远远超过了需要。

s.chars().mapToObj(c -> (char) c).collect(Collectors.groupingBy(c -> c, Collectors.counting()));

关于频率,Java中的字符由ASCII码支持。因此,您可以将字符彼此相减以获得ASCII值。感谢@BackSlash的流实现。

相关问题