java题,懂英文的看看吧
来源:学生作业帮 编辑:大师作文网作业帮 分类:综合作业 时间:2024/11/11 08:08:18
java题,懂英文的看看吧
Write a method called maxFrequency which takes a string (length >=1) as parameter (containing characters from a to z; only small caps),calculates frequencies of characters in the string and returns the character with maximum frequency.For example,if the parameter string is "abcabcabca",the method returns 'a'.
Write a method called maxFrequency which takes a string (length >=1) as parameter (containing characters from a to z; only small caps),calculates frequencies of characters in the string and returns the character with maximum frequency.For example,if the parameter string is "abcabcabca",the method returns 'a'.
怎么问两次?我已经回答过一次了,最简单的方法,时间复杂度为O(n),n为字符串长度,一次循环即可!
public char maxFrequency(String str) {
int count = new int[26]; //用于记录26个英文字母出现的频率,count[0]对应a出现的次数
int max = 0;
int index = -1;
for (int i = 0; i < str.length(); i++) { //读取str中每个字符
char c = str.charAt(i);
int j = c - 'a';//c - 'a'为该字符与字符'a'的差值,作为count的下标,将count数组对应位置加1
count[j]++;
if (count[j] > max) { //随时记录最大值的索引
max = count[j];
index = j;
}
}
return (char) ('a' + index); //这个索引就是这个字符与‘a’的差值,用'a'加上这个索引,再强制转换成char返回即可
}
public char maxFrequency(String str) {
int count = new int[26]; //用于记录26个英文字母出现的频率,count[0]对应a出现的次数
int max = 0;
int index = -1;
for (int i = 0; i < str.length(); i++) { //读取str中每个字符
char c = str.charAt(i);
int j = c - 'a';//c - 'a'为该字符与字符'a'的差值,作为count的下标,将count数组对应位置加1
count[j]++;
if (count[j] > max) { //随时记录最大值的索引
max = count[j];
index = j;
}
}
return (char) ('a' + index); //这个索引就是这个字符与‘a’的差值,用'a'加上这个索引,再强制转换成char返回即可
}