fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Map;
  5. import java.util.HashMap;
  6.  
  7. public class Main {
  8. private static boolean isLetter(char c) {
  9. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  10. }
  11.  
  12. private static void increaseFrequency(Map<String, Integer> words, String currentWord) {
  13. if (words.containsKey(currentWord)) {
  14. words.put(currentWord, words.get(currentWord) + 1);
  15. } else {
  16. words.put(currentWord, 1);
  17. }
  18. }
  19.  
  20. private static boolean isMoreFrequent(StringBuilder currentWord, StringBuilder recurrentWord, int currentOcurance, int maxOcurance) {
  21. return (currentOcurance > maxOcurance) || (currentOcurance == maxOcurance && (recurrentWord == null || recurrentWord.compareTo(currentWord) > 0));
  22. }
  23.  
  24. private static void updateRecurrentWord(StringBuilder recurrentWord, StringBuilder currentWord, int[] maxOcurance, int currentOcurance) {
  25. if (isMoreFrequent(currentWord, recurrentWord, currentOcurance, maxOcurance[0])) {
  26. recurrentWord.replace(0, recurrentWord.length(), currentWord.toString());
  27. maxOcurance[0] = currentOcurance;
  28. }
  29. }
  30.  
  31. public static String frequestWord(BufferedReader reader) throws IOException {
  32. Map<String, Integer> words = new HashMap<>();
  33. StringBuilder recurrentWord = new StringBuilder();
  34. int[] maxOcurance = new int[1];
  35. StringBuilder currentWord = new StringBuilder();
  36. boolean wasLetter = false;
  37. while (reader.ready()) {
  38. char letter = (char)reader.read();
  39. if (isLetter(letter)) {
  40. currentWord.append(letter);
  41. wasLetter = true;
  42. } else if (wasLetter) {
  43. increaseFrequency(words, currentWord.toString());
  44. updateRecurrentWord(recurrentWord, currentWord, maxOcurance, words.get(currentWord.toString()));
  45. currentWord = new StringBuilder();
  46. wasLetter = false;
  47. }
  48. }
  49.  
  50. return recurrentWord.toString();
  51. }
  52.  
  53. public static void main(String[] args) throws IOException {
  54. System.out.println(frequestWord(reader));
  55. }
  56. }
Success #stdin #stdout 0.09s 54688KB
stdin
please write a text
write a
stdout
write