Tuesday, March 24, 2015

Find most frequent word in a string

Find most frequent word in a string.
For example, "I have a dream and dream.Cool.", the most frequent word is "dream".

Solution:
1. split string with "." and " ";
2. store the splited string into a hashmap, key is the word, value is the number this word appears;
3. find the largest value.
public class MostFrequentWordInString {
    public static void main(String[] args) {
        String str = "I have.a dream and dream.Cool.";
        mostFrequentWord(str);
    }
 
    public static String mostFrequentWord(String str) {
        String[] lists = str.split("\\.| ");
  
        HashMap map = new HashMap();
        for(int i = 0; i < lists.length; i++) {
            if(!map.containsKey(lists[i])) {
                map.put(lists[i], 1);
            }else {
                map.put(lists[i], map.get(lists[i]) + 1);
            }
        }
  
        Map.Entry max = null;
        for(Map.Entry i : map.entrySet()) {
            if(max == null) {
                max = i;
            }
            if((int)i.getValue() > (int)max.getValue()) {
                max = i;
            }
        }
  
        System.out.println("Most frequent word is: " + (String)max.getKey());
        return (String)max.getKey();
    }
}

No comments:

Post a Comment