819. Most Common Word

Question

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

Example:

Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.


Note:

1 <= paragraph.length <= 1000.
0 <= banned.length <= 100.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
There are no hyphens or hyphenated words.
Words only consist of letters, never apostrophes or other punctuation symbols.

Solution

  • Method 1: HashMap
    class Solution {
        public String mostCommonWord(String paragraph, String[] banned) {
            paragrap
            h = paragraph.replaceAll("[\\!\\?',;\\.]", " ");
            String[] tokens = paragraph.toLowerCase().split(" ");
            Map<String, Integer> map = new HashMap<>();
            int max = 0;
            Set<String> ban = new HashSet<>();
            for(String word: banned) ban.add(word);
            for(String token : tokens){
                token = token.trim();
                if(ban.contains(token) || token.length() == 0) continue;
                System.out.println(token);
                int occur = map.containsKey(token) ? map.get(token): 0;
                map.put(token, occur + 1);
                max = Math.max(max, occur + 1);
            }
            for(Map.Entry<String, Integer> entry : map.entrySet()){
                if(entry.getValue() == max) return entry.getKey();
            }
            return "";
        }
    }
    
    • Method 2: Use StringBuilder, O(n)
      class Solution {
        public String mostCommonWord(String paragraph, String[] banned) {
            paragraph += ".";
            Set<String> set = new HashSet<>();
            for(String ban : banned) set.add(ban);
            StringBuilder sb = new StringBuilder();
            Map<String, Integer> map = new HashMap<>();
            int max = 0;
            String res = "";
            for(char c : paragraph.toCharArray()){
                if(Character.isLetter(c)){
                    sb.append(Character.toLowerCase(c));
                }else if(sb.length() > 0){
                    String token = sb.toString();
                    if(!set.contains(token)){
                        int occur = map.getOrDefault(token, 0);
                        if(occur + 1 > max){
                            max = occur + 1;
                            res = token;
                        }
                        map.put(token, occur + 1);
                    }
                    sb = new StringBuilder();
                }
            }
            return res;
        }
      }
      

Amazon session

class Solution {
    private static class Node{
        String val;
        int freq;
        public Node(String val){
            this.val = val;
        }
    }
    public String mostCommonWord(String paragraph, String[] banned) {
        Map<String, Node> map = new HashMap<>();
        PriorityQueue<Node> pq = new PriorityQueue<>((a, b)->{
            return b.freq - a.freq;
        });
        Set<String> ban = new HashSet<>();
        for(String b : banned) ban.add(b);
        char[] arr = paragraph.toCharArray();
        int pre = Character.isLetter(arr[0]) ? 0: 1;
        List<String> tokens = new ArrayList<>();
        for(int i = 1; i < arr.length; i++){
            if(!Character.isLetter(arr[i])){
                tokens.add(paragraph.substring(pre, i));
                pre = i + 1;
            }
        }
        if(pre != arr.length) tokens.add(paragraph.substring(pre, arr.length));
        for(String token : tokens){
            int len = token.length();
            String cur = token.toLowerCase();
            if(!ban.contains(cur) && !cur.equals(" ") && cur.length() != 0 ){
                Node node = map.getOrDefault(cur, new Node(cur));
                node.freq++;
                map.put(cur, node);
            }
        }
        for(Node node : map.values()){
            pq.offer(node);
        }
        return pq.peek().val;
    }
}