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
- First, split the words individually from the sentence and store them in array.
- Iterate through the array and store the words in Set.
- Set returns false if the element is already present.
- 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>