Find duplicate word in sentence using java

Find duplicate word in sentence using java

Question

Given a sentence, find duplicate word in sentence and print the position of the word of the duplicate word.

 

Algorithm

  1. First, split the words individually from the sentence and store them in array.
  2. Iterate through the array and store the words in Set.
  3. Set returns false if the element is already present.
  4. If false, then print the word and position of the word.

Program

import java.util.Scanner;
import java.util.Set;
import java.util.HashSet;
class RepeatElement 
{ 
	public static void main(String[] args) 
	{  
	    String s;
	    int count=1;							// position 
		Scanner sc = new Scanner(System.in); 
		s=sc.nextLine();

	    String c[] = s.split("\\s+");			// split the string by empty spaces

/* split is used to seperate each word from the sentence*/

     Set<String> store = new HashSet();			// String set

     for(String a:c)  							// iterating throught each word
     { 
	     if(store.add(a)== false)				// if the element already present in set
	     System.out.println("duplicate"+a+count);
	     count++; 

      } 
    } 
}
</pre>

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x