Highest Occuring Character
- Get link
- X
- Other Apps
For a given a string(str), find and return the highest occurring character.
Sample Input 1:
abdefgbabfba
Sample Output 1:
b
Approach 1 -
import java.util.Scanner;
public class HighestOccurence {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String st = s.nextLine();
char c = highestOccuringChar(st);
System.out.println(c);
}
public static char highestOccuringChar(String str) {
char chh=' ';
int max=0;
int l=str.length();
for(int i=97;i<=122;i++)
{
int c=0;
char ch1=(char)i;
for(int j=0;j<l;j++)
{
char ch=str.charAt(j);
if(ch1==ch)
{
c++;
}
}
if(c>max)
{
max=c;
chh=ch1;
}
}
return chh;
}
}
Approach 2 -
public class Solution {
public static char highestOccuringChar(String str) {
int N = 256;
int ctr[] = new int[N];
int l = str.length();
for (int i = 0; i < l; i++)
ctr[str.charAt(i)]++;
int max = -1;
char result = ' ';
for (int i = 0; i < l; i++) {
if (max < ctr[str.charAt(i)]) {
max = ctr[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
}
- Get link
- X
- Other Apps
Comments
Post a Comment