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