Answer to Question #249464 in Java | JSP | JSF for rock

Question #249464

Create a Java program to find which word has the maximum occurrence and

replace that word by a special symbol, say *.


1
Expert's answer
2021-10-11T00:05:43-0400
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Main
{
    public static void insert(Word head, String S)
    {
        Word cur = head;


        for (char x: S.toCharArray())
        {
            cur.character.putIfAbsent(x, new Word());
            cur = cur.character.get(x);
        }
        cur.key = S;
        cur.count += 1;
    }
    public static int preorder(Word curr, int maxCount, StringBuilder key)
    {
        if (curr == null) {
            return maxCount;
        }


        for (var entry: curr.character.entrySet())
        {
            if (maxCount < entry.getValue().count)
            {
                key.replace(0, key.length(), entry.getValue().key);
                maxCount = entry.getValue().count;
            }
            maxCount = preorder(entry.getValue(), maxCount, key);
        }


        return maxCount;
    }


    public static void main(String[] args)
    {
        List<String> dict = Arrays.asList(
                "star", "java", "run", "we", "rain", "rain", "answer",
                "come", "string", "str", "star", "code", "home",
                "star", "codes", "answer", "star", "rain", "string",
                "start", "drive", "string", "tree", "star"
        );
        Word head = new Word();
        for (String word: dict) {
            insert(head, word);
        }


        int count = 0;
        StringBuilder key = new StringBuilder();
        count = preorder(head, count, key);


        System.out.println("Word : " + key);
        System.out.println("Count: " + count);
    }
}


class Word
{
    String key;
    int count;
    Map<Character, Word> character = null;
    Word() {
        character = new HashMap<>();
    }

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS