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

问题描述 投票:1回答:2

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

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

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

我很困惑。有人可以帮我吗?

java arrays string data-structures
2个回答
0
投票

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

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


0
投票

在我看来,你可以用更简单的方式重写你的解决方案。除非我误解它,否则这个解决方案远比它需要的复杂得多。

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

至于频率,Java中的字符由ASCII码支持。因此,您可以相互减去字符以获取ASCII值。感谢@BackSlash的流实现。

© www.soinside.com 2019 - 2024. All rights reserved.