Answer to Question #254009 in Java | JSP | JSF for hema

Question #254009

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-20T16:38:41-0400
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;


public class Main
{
    public static void insert(Word hd, String str)
    {
        Word current = hd;
        for (char n: str.toCharArray()){
            current.character.putIfAbsent(n, new Word());
            current = current.character.get(n);
        }
        current.key = str;
        current.count += 1;
    }
    public static int preorder(Word current, int max_ct, StringBuilder key)
    {
        if (current == null) {
            return max_ct;
        }
        for (var entry: current.character.entrySet()) {
            if (max_ct < entry.getValue().count)
            {
                key.replace(0, key.length(), entry.getValue().key);
                max_ct = entry.getValue().count;
            }
            max_ct = preorder(entry.getValue(), max_ct, key);
        }


        return max_ct;
    }




    public static void main(String[] args)
    {
        List<String> dict = Arrays.asList(
                "c++", "java", "python", "c", "python", "python", "c", "c++", "c", "c",
                "c++", "c#", "c#", "c++", "c", "python",
                "python", "c", "python", "c#", "c++"
        );
        Word hd = new Word();
        for (String word: dict) {
            insert(hd, word);
        }




        int count = 0;
        StringBuilder key = new StringBuilder();
        count = preorder(hd, 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