Coding Challenge Day- 12: Problem 1: Find the duplicate words and their number of occurrences in a string

Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 12: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem : Find the duplicate words and their number of occurrences in a string

Sample input: “coding yesterday coding today coding always”
Output: coding:3

Sample input: “Betty bought some butter and butter was bitter so Betty bought some more butter to make the bitter butter better”
Output: some:2
betty:2
butter:4
bought:2
bitter:2

Solution:

I learnt to solve this one from HERE

package string;

import java.util.HashMap;

import java.util.Set;

public class Program010duplicate_word_in_string {
	
	public static void duplicate_words (String str){
		String words[]= str.split(" ");
		
		HashMap<String , Integer> list_of_words= new HashMap<String, Integer>();
		
		for(String word: words){
			
			if(list_of_words.containsKey(word.toLowerCase())){
				
				list_of_words.put(word.toLowerCase(), list_of_words.get(word.toLowerCase())+1);
			}
			
			else{
				
				list_of_words.put(word.toLowerCase(), 1);
			}
			
		}
		
		Set<String> unique_words= list_of_words.keySet();
		
		for(String word : unique_words){
			if(list_of_words.get(word)>1 ){
				System.out.println(word+ ":" + list_of_words.get(word));
			}
		}
		
	}
	
	public static void main (String [] args){
		duplicate_words("coding yesterday coding today coding always");
	}

}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: