I have a problem because I only take 60 points per evaluation, I do not know how to display the lexicographic minimum if I have for example two words the same number of times. I practically have to display the most common word in a text, if there are two words that appear the same number of times to display the lexicographic minimum. I don't really know how to use HashMap to do this, a fix? This is my code!
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] input = currentLine.replaceAll("[^a-zA-Z]", " ").toLowerCase().split(" ");
currentLine.replace('\n', ' ');
for (int i = 0; i < input.length; i++) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
currentLine = reader.readLine();
}
String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
if (m.getValue() > count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
}
else if (m.getValue() == count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
if ()
}
}
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You could also compare the mostRepeatedWord
with current key in case of a tie in the loop itself like below:
String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
if (m.getValue() > count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
} else if (m.getValue() == count) {
String key = m.getKey();
if ( key.compareTo(mostRepeatedWord) ) < 0 {
mostRepeatedWord = key;
}
}
}