Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence.
Examples:
Input : str = " Hi, I am Hritik and I am a programmer. "
Output: I am
Explanation: We are printing duplicate words in the given Expression.
Input : str = " Ironman is alive. "
Output: There is no Duplicate Word.
Explanation: There are no duplicate words present in the given Expression.
Approach 1:
- Get the Expression.
- Store all Words in an Array.
- Splitting word using regex ‘\\W’. (use of regex)
- Iterating in the array and storing words and all the number of occurrences in the Map.
- Now, In the Map, If the number of occurrences is more than 1 then we are printing the word.
Below is the implementation of the above approach:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
String expression
= "Hi, I am Hritik and I am a programmer" ;
String[] words = expression.split( "\\W" );
Map<String, Integer> word_map = new HashMap<>();
for (String word : words) {
if (word_map.get(word) != null ) {
word_map.put(word, word_map.get(word) + 1 );
}
else {
word_map.put(word, 1 );
}
}
Set<String> word_set = word_map.keySet();
for (String word : word_set) {
if (word_map.get(word) > 1 )
System.out.println(word);
}
}
}
|
Approach 2:
- Get the Expression.
- Store all Words in an Array.
- Splitting word using regex ‘\\W’. (use of regex)
- Matching every word of the array with other words through iteration.
- If words matched then adding words in a Set because set removes the repeated words added by the flow of iteration.
- Finally, we are printing the set.
Below is the implementation of the above approach:
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
String expression
= "Hi, I am Hritik and I am a programmer" ;
String[] words = expression.split( "\\W" );
Set<String> set = new HashSet<>();
for ( int i = 0 ; i < words.length - 1 ; i++) {
for ( int j = 1 ; j < words.length; j++) {
if (words[i].equals(words[j]) && i != j) {
set.add(words[i]);
}
}
}
System.out.println(set);
}
}
|