Josif_tepe

Untitled

Jan 9th, 2026
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.*;
  3.  
  4. public class Frequency {
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.         String s = scanner.nextLine().trim();
  8.         Map<String, Integer> freq = new HashMap<>();
  9.         for(int i = 0; i < s.length(); i++) {
  10.             String tmp = "";
  11.  
  12.             for(int j = i; j < s.length(); j++) {
  13.                 tmp += s.charAt(j);
  14.  
  15.                 freq.put(tmp, freq.getOrDefault(tmp, 0) + 1);
  16.             }
  17.         }
  18.  
  19.         String res = "";
  20.         int bestFreq = -1;
  21.  
  22.         for(Map.Entry<String, Integer> e: freq.entrySet()) {
  23.             String c = e.getKey();
  24.             int val = e.getValue();
  25.  
  26.             if(val > bestFreq) {
  27.                 bestFreq = val;
  28.                 res = c;
  29.             }
  30.             else if(val == bestFreq) {
  31.                 if(c.length() > res.length()) {
  32.                     res = c;
  33.                 }
  34.                 else if(c.length() == res.length()) {
  35.                     if(c.compareTo(res) < 0) {
  36.                         res = c;
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.  
  42.         System.out.println(res);
  43.  
  44.         scanner.close();
  45.     }
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment