-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathJavaRegex2.java
More file actions
75 lines (51 loc) · 2.15 KB
/
JavaRegex2.java
File metadata and controls
75 lines (51 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Java Regex 2 - Duplicate Words
When we write something, it is easy to repeat words by mistake. For example: Monmoy loves to to code. Here, "to"
is written multiple times.
Using Regex, we can easily identify the repeated pattern in a given text. In this problem, you will be given a text.
Your task is to identify the consecutively repeated words and delete them after the first occurrence of the word.
Complete the code in the editor to solve this problem. Don't modify any extra lines. You will get the wrong answer
if you modify more than 3 lines.
To restore the original code in the editor, create a new buffer by clicking on the top-left button in the editor.
Input Format
The first line of input contains an integer N, representing the number of testcases. The next N lines contain a
string of English letters and whitespaces.
Constraints
In each line, there will be at most 104 English letters and whitespaces.
1≤N≤100
Output Format
Print the input string after deleting the consecutive words after the first occurrence of the word.
Sample Input
4
Goodbye bye bye world world world
Swapnil went went to to to his business
Rana is is the the best player in eye eye game
in inthe
Sample Output
Goodbye bye world
Swapnil went to his business
Rana is the best player in eye game
in inthe
*/
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateWords {
public static void main(String[] args) {
String regex = "\\b(\\w+)(\\s\\1)+\\b";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Scanner in = new Scanner(System.in);
int numSentences = Integer.parseInt(in.nextLine());
while (numSentences-- > 0) {
String input = in.nextLine();
Matcher m = p.matcher(input);
// Check for subsequences of input that match the compiled pattern
while (m.find()) {
input = input.replaceAll(m.group(), m.group(1));
}
// Prints the modified sentence.
System.out.println(input);
}
in.close();
}
}