java - 我们如何计算字符串中字符的频率
问题描述
我正在研究问题的解决方案。
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']++;
能够计算元素的频率。以及如何将其存储回该位置。
我对此感到困惑。任何人都可以帮我吗?
解决方案
小写 ASCII 字母占据ASCII 表的连续部分,从索引 97 到 122。如果您的输入由小写 ASCII 字母组成,则表达式str.charAt(i) - 'a'
将计算为范围[0, 25]中的值。a
将变为0,b
将变为1,c
将变为2,依此类推。
然而,这种方法对于非小写 ASCII 字符会失败,例如,大写“A”字母的值为 65,因此'A' - 'a'
将65 - 97
尝试访问负数组索引。
推荐阅读
- trac - trac 默认 CC 插件的配置选项是什么
- debugging - 如何进行chrome调试?
- django - 对 Nginx 的任何请求的 504 网关超时,具有大量免费资源
- ios - Xamarin Form 滑块自定义,用于更改 iOS 中滑块的粗细
- php - 在单选按钮的选定值上获取 html 表单
- c - 如何升到 A (2x2) 矩阵的 n 次方?
- office365 - 当我调用 Microsoft Graph api - CalendarView with delta 函数时,有什么方法可以不显示发生事件
- javascript - IBM 门户页面上的导航问题
- java - 如何以编程方式更改 EditText 对象的宽度?
- java - 如何在同一个休眠会话中从数据库表中获取更新的值