/** * Returns the character that occurs most frequently in * the given string. I
ID: 3725533 • Letter: #
Question
/** * Returns the character that occurs most frequently in * the given string. If several characters occur with * the same maximum frequency, returns the one that * occurs first in the string. The string must be nonempty. * <p> * For example, given the string "banana" the method returns 'a'. * Given the string "abcbcbbcca" the method returns 'b'. * @param s * nonempty string * @return * most frequently occurring character in s */ public static char findMostFrequentCharacter(String s) { // TODO return 0; }
Explanation / Answer
public class Test {
/**
* Returns the character that occurs most frequently in
* the given string. If several characters occur with
* the same maximum frequency, returns the one that
* occurs first in the string. The string must be nonempty.
* <p>
* For example, given the string "banana" the method returns 'a'.
* Given the string "abcbcbbcca" the method returns 'b'.
* @param s
* nonempty string
* @return
* most frequently occurring character in s
*/
public static char findMostFrequentCharacter(String s)
{
// TODO
int count[] = new int[26];
for(int i=0; i<s.length(); i++) {
int index = s.charAt(i) - 'a';
count[index]++;
}
int max = 1;
char c = ' ';
for(int i=0; i<26; i++) {
if(max < count[i]) {
max = count[i];
c = (char)(i + 'a');
}
}
return c;
}
/**
* Returns a string with runs of consecutive characters removed.
* For example, <code>eliminateRuns("abbbccbbd")</code> returns
* the string "abcbd".
* @param s
* given string (possibly empty)
* @return
* string similar to s but with runs removed
*/
public static String eliminateRuns(String s)
{
// TODO
if(s == null || s.length() < 2)
return s;
char c = s.charAt(0);
String result = "";
result = result + c;
for(int i=1; i<s.length(); i++) {
if(c != s.charAt(i)) {
c = s.charAt(i);
result = result + c;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(findMostFrequentCharacter("abbbccbbd"));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.