Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class MostFrequentSubstring {
- public static void main(String[] args) {
- Scanner std = new Scanner(System.in);
- String str = std.nextLine();
- HashMap<String, Integer> tabela = new HashMap<>();
- String search;
- for (int i = 0; i < str.length(); i++) {
- for (int j = i + 1; j <= str.length(); j++) {
- search = str.substring(i, j);
- if (tabela.containsKey(search)) {
- int g = tabela.get(search);
- tabela.put(search, ++g);
- } else
- tabela.put(search, 1);
- }
- }
- int max = 0;
- String maxSub = "";
- for (Map.Entry<String, Integer> entry : tabela.entrySet()) {
- if (entry.getValue() > max) {
- max = entry.getValue();
- maxSub = entry.getKey();
- } else if (entry.getValue() == max) {
- if (entry.getKey().length() > maxSub.length()) {
- maxSub = entry.getKey();
- } else if (entry.getKey().length() == maxSub.length()) {
- int n = 0;
- for (int i = 0; i < entry.getKey().length(); i++) {
- n += entry.getKey().charAt(i);
- }
- int m = 0;
- for (int i = 0; i < maxSub.length(); i++) {
- m += maxSub.charAt(i);
- }
- if (n < m)
- maxSub = entry.getKey();
- }
- }
- }
- System.out.println(maxSub);
- }
- }
Add Comment
Please, Sign In to add comment