819. Most Common Word

819. Most Common Word

import java.util.Hashtable;
import java.util.List;
import java.util.Set;
class Solution {
    public String mostCommonWord(String paragraph, String[] banned) {
	String paragraphProcessed = paragraph.replace("!", "").replace("?", "").replace("'", "").replace(",", "").replaceAll(";", "").replace(".", "");

		String input[] = paragraphProcessed.split(" ");
		for (int i = 0; i < input.length; i++)
			input[i] = input[i].toLowerCase();
		Hashtable f = new Hashtable();
		for (String s : input) {
			if (f.get(s) == null)
				f.put(s, 1);
			else
				f.replace(s, f.get(s) + 1);
		}

		for (int i = 0; i < banned.length; i++) {
			if (f.get(banned[i]) != null)
				f.remove(banned[i]);
		}

		int mostFrequ = Integer.MIN_VALUE;
		String mostFrequString = "";
		Set keys = f.keySet();
		for (String key : keys) {
			if (f.get(key) > mostFrequ) {
				mostFrequ = f.get(key);
				mostFrequString = key;
			}
		}
		return mostFrequString;
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s