In: Computer Science
public static char mostFrequent(String str) {
if(str.length()==0) {
return
'0';
}
String temp="";
for (int i = 0; i <
str.length(); i++) {
if(!temp.contains(String.valueOf(str.charAt(i)))) {
temp += String.valueOf(str.charAt(i));
}
}
char[]
tempArray=stringToArray(temp);
int[] countArr=new
int[tempArray.length];
int max=0;
for(int
i=0;i<tempArray.length;i++) {
int
cnt=numOccurences(tempArray[i],str);
countArr[i]=cnt;
if(max<cnt)
{
max=cnt;
}
}
for(int
i=0;i<tempArray.length;i++) {
if(max==countArr[i]) {
return tempArray[i];
}
}
return '0';
}
CAN SOMEONE PLEASE COMMENT OUT THIS CODE, I DON'T KNOW EXACTLY WHAT IT DOES, THANKS.
below is well commented code
This code basically returns the character in string having maximum
frequency.
public static char mostFrequent(String str) {
//check if string length is zero, then return 0 as
answer
if(str.length()==0) {
return '0';
}
String temp="";
// this loop basically adds all the unique characters of
str to temp
for (int i = 0; i < str.length(); i++) {
// checks if a char is in temp or not, if not add it to
temp
if(!temp.contains(String.valueOf(str.charAt(i)))) {
temp += String.valueOf(str.charAt(i));
}
}
// convert string into char array
char[] tempArray=stringToArray(temp);
// new count array of integer
int[] countArr=new int[tempArray.length];
int max=0;
for(int i=0;i<tempArray.length;i++) {
// count occurence of each character in str
int cnt=numOccurences(tempArray[i],str);
countArr[i]=cnt;
//update maximum count
if(max<cnt) {
max=cnt;
}
}
for(int i=0;i<tempArray.length;i++) {
//return element with maximum count
if(max==countArr[i]) {
return tempArray[i];
}
}
return '0';
}
Thank you, please upvote