3. Find duplicates characters in a string

3. Find duplicates characters in a string


Problem link :- click here


package programs;

import java.util.HashMap;
import java.util.Map;

public class String__3
{
	/*
	 	we can use hash map to find the duplicates
	 */
	
	static void printDuplicates(String s)
	{
		String st = s.toLowerCase();
		char str[] = st.toCharArray();
		
		Map<Character, Integer> map = new HashMap<>();
		
		//adding the characters to the map
		for(char i : str)
		{
			if( map.containsKey(i) )
				map.put( i, map.get(i) + 1 );
			else
				map.put(i, 1);
		}
		
		//printing the duplicates elements
		for(char i : str)
		{
			if( map.get(i) >= 2 )
			{
				System.out.println( i + " has occured " + map.get(i) + " times");
				//to avoid multiple printing 
				map.put(i, 1);
			}
		}
	}

	public static void main(String[] args)
	{
		String s = "Murali venkat J";
		
		System.out.println("Given string is : " + s );
		System.out.println("Duplicates are : ");
		printDuplicates(s);
	} 

}

Time complexity :- O(n)
Space complexity :- O(n)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree