-1

I have this code that gives us all the substrings of a string of my choice :

static void subString(char str[], int n) {
    
    for (int len = 1; len <= n; len++) {
       
        for (int i = 0; i <= n - len; i++) {
           
            int j = i + len - 1;
            for (int k = i; k <= j; k++) {
                System.out.print(str[k]);
            }

           System.out.println();
        }

How can I rewrite it in a way that show us the most frequent substring?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

0

If you just want a count of all substrings, you can do something like this

public static void main( String[] args ) {
    char[] ch = {'o','v', 'o', 'v'};
    Map<String, Integer> count = subString(ch, ch.length);

    for(var entry : count.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
}

public static Map<String, Integer> subString(char ch[], int n) {
    Map<String, Integer> count = new HashMap<>();

    for(int i = 0; i < n; i++)
        for(int j = 1; j <= n-i; j++) {
            String str = String.valueOf(ch, i, j);
            count.put(str, count.getOrDefault(str, 0)+1);
        }

    return count;
}
arjunkhera
  • 929
  • 6
  • 23