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
Java Q-2
program
Fgh
Armstrong number
Link document
Java - Swap two numbers without using temp var
MinMaxArray
Hilbert Curve
Has A
pk3