fork download
  1. import java.io.*;
  2. import java.util.*;
  3. class Solution {
  4. static String mostFrequentNonBanned(String paragraph, String[] banned){
  5.  
  6. String normallized = paragraph.toLowerCase().replaceAll("[^a-z]","");
  7. String[] words = normallized.split("\\s+");
  8. Set<String> bannedSet= new HashSet<>(Arrays.asList(banned));
  9.  
  10.  
  11. Map<String,Integer> freq = new HashMap<>();
  12. for(String word : words ){
  13. if(!bannedSet.contains(word) && word.length()> 0){
  14. freq.put(word,freq.getOrDefault(word,0)+1);
  15. }
  16. }
  17. String result= "";
  18. int maxCount = 0;
  19.  
  20. for(String word: freq .keySet()){
  21. int count = freq.get(word);
  22. if(count>maxCount||(count ==maxCount && word.compareTo(result)< 0)){
  23. maxCount= count;
  24. result= word;
  25. }
  26. }
  27. return result;
  28. }
  29.  
  30. public static void main(String[] argv) {
  31. System.out.println(mostFrequentNonBanned("Bob hit a ball, the hit BALL flew far after it was hit.", new String[]{"hit"}).equals("ball"));
  32. System.out.println(mostFrequentNonBanned("It's a beautiful day, isn't it? Beautiful day indeed!", new String[]{"it's", "it"}).equals("beautiful"));
  33. System.out.println(mostFrequentNonBanned("Apple orange apple ORANGE", new String[]{}).equals("apple"));
  34. System.out.println(mostFrequentNonBanned("Wow! This is WOW, just wow... right?", new String[]{"right"}).equals("wow"));
  35. System.out.println(mostFrequentNonBanned("Hello", new String[]{}).equals("hello"));
  36. System.out.println(mostFrequentNonBanned("", new String[]{"anything"}).equals(""));
  37. System.out.println(mostFrequentNonBanned("test test test pass pass", new String[]{"test"}).equals("pass"));
  38.  
  39. }
  40.  
  41. }
Success #stdin #stdout 0.09s 55816KB
stdin
Standard input is empty
stdout
false
false
false
false
true
true
false