Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Most Common Word
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; /* paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] Output: "ball" */ class Rextester { public static void main(String args[]) { System.out.println(mostCommonWord("Bob. hit, ball",new String[]{"hit"})); } public static String mostCommonWord(String paragraph, String[] banned) { String[] tokens = paragraph.split("\\W"); Set<String> set = new HashSet<>(Arrays.asList(banned)); Map<String,Integer> map = new HashMap<>(); for(String token:tokens){ if(token.length()<1) continue; String word = stripToken(token.toLowerCase()); if(set.contains(word)) continue; map.put(word, map.get(word)==null ? 1:map.get(word)+1 ); } Map.Entry<String,Integer> max = null; for(Map.Entry<String,Integer> entry:map.entrySet()){ if(max==null || entry.getValue().compareTo(max.getValue()) > 0) max = entry; } return max.getKey(); } public static String stripToken(String token){ if(token.length()<1) return null; char lastChar = token.toCharArray()[token.length()-1]; if( lastChar>='a' && lastChar<='z') return token; return token.substring(0, token.length()-1); } }
run
|
edit
|
history
|
help
0
Add Index of max number in an array
ClientesJava v2
Odd Occurence Problem Template
Merge Sort in Java
Class multiple
Java Object structure dumper (iterative)
Complex number multiplication (leetcode)
jb15.0
Sumod
bit right 2