Skip to content

Commit cf52dd4

Browse files
committed
Remove duplicate words in a string
1 parent 2f7a30e commit cf52dd4

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Java/Strings/DuplicateWords.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
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.
3+
4+
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 33 lines.
5+
6+
To restore the original code in the editor, create a new buffer by clicking on the top-left button in the editor.
7+
8+
Input Format
9+
The first line of input contains an integer NN, representing the number of testcases. The next NN lines contain a string of English letters and whitespaces.
10+
Constraints
11+
In each line, there will be at most 104104 English letters and whitespaces.
12+
1≤N≤1001≤N≤100
13+
Output Format
14+
Print the input string after deleting the consecutive words after the first occurrence of the word.
15+
*/
16+
17+
18+
import java.util.Scanner;
19+
import java.util.regex.Matcher;
20+
import java.util.regex.Pattern;
21+
22+
public class DuplicateWords
23+
{
24+
public static void main(String[] args){
25+
26+
String pattern = "(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+";
27+
Pattern r = Pattern.compile(pattern, Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
28+
29+
Scanner in = new Scanner(System.in);
30+
int testCases = Integer.parseInt(in.nextLine());
31+
while(testCases>0){
32+
String input = in.nextLine();
33+
Matcher m = r.matcher(input);
34+
boolean findMatch = true;
35+
while(m.find( )){
36+
input = input.replaceAll(input,input.replaceFirst("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+","$1"));
37+
findMatch = false;
38+
}
39+
System.out.println(input);
40+
testCases--;
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)