Create a Java program to find which word has the maximum occurrence and
replace that word by a special symbol, say *.
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<>();
}
}
Comments
Leave a comment