Friday, November 6, 2015

Given a string, print the character which appears the maximum number of times in the string. The string will contain only ascii characters. If there is a tie in the maximum number of times a character appears in the string, print the character which appears first in the string.

Solution 1.

import java.util.*;
import java.io.*;

public class MaxCharOccuranceMap {

/**
* *
* @param args
*/
public static void main(String[] args) {

BufferedReader buff = new BufferedReader(new InputStreamReader(
System.in));
String s = "";

try {
while ((s = buff.readLine()) != null) {
getMaxoccurance(s);
}
} catch (IOException e) {
e.printStackTrace();
}

}

public static void getMaxoccurance(String s) {
int max = 1;
Map map = new TreeMap(); 

for (int k = 0; k < s.length(); k++) {
char c = s.charAt(k);
if (c != ' ') {
if (map.containsKey(c)) {
map.get(c);
int val = map.get(c);
val = val + 1;
if (val > max) {
max = val;
}
map.put(c, val);
} else {
map.put(c, 1);
}
}
}
/*
* map.entrySet() returns Set as map is declared as
* map.entrySet().iterator() returns iterator of type
* Map.Entry
*/
Iterator> itr = map.entrySet().iterator();
List list = new ArrayList();
while (itr.hasNext()) {
Map.Entry entry = (Map.Entry) itr
.next();
if (entry.getValue() == max) {
System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
list.add(entry.getKey());

}

}
if (list.size() > 0) {
System.out.print(list);
}
}
}

Solution 2.

public class MaxOccuringCahrsInStr {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is Sarthak Gupta";
printMaxOccuringChars(str);
}
static void printMaxOccuringChars(String str) {
char[] arr = str.toCharArray();
/* Assuming all characters are ascii */
int[] arr1 = new int[256];
int maxoccuring = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != ' ') { // ignoring space
int val = (int) arr[i];
arr1[val]++;
if (arr1[val] > maxoccuring) {
maxoccuring = arr1[val];
}
}
}
for (int k = 0; k < arr1.length; k++) {
if (maxoccuring == arr1[k]) {
char c = (char) k;
System.out.print(c + " ");
}
}
}
}

No comments:

Post a Comment