Reputation: 1
Question details:
I'm solving the HackerRank Regex - Duplicate Words problem in Java where the goal is to use regular expressions to remove repeated words while retaining the first occurrence, regardless of case. For example, the input "I love Love to To tO code" should output as "I love to code."
For solving the problem we have to complete the below three lines:
Write a RegEx to match repeated words.
Add a compile argument to make the RegEx case-insensitive.
Use replaceAll to replace duplicates with the first occurrence, keeping the original case of the first word.
Problems Code [which I've solved]:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateWords {
public static void main(String[] args) {
// RegEx to match repeated words
String regex = "\\b(\\w+)\\b(?:\\s+\\b\\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()) {
// Replace the repeated words with a single occurrence of the word
input = input.replaceAll(m.group(), m.group(1));
}
// Prints the modified sentence.
System.out.println(input);
}
in.close();
}
}
Input [stdin]:
5
Goodbye bye bye world world world
Sam went went to to to his business
Reya is is the the best player in eye eye game
in inthe
Hello hello Ab aB
Output [I'm getting]:
Goodbye bye world
Sam went to his business
Reya is the best player in eye game
in inthe
Hello Ab
Expected Output [The output that needs to be shown on the output screen]:
Goodbye bye world
Sam went to his business
Reya is the best player in eye game
in inthe
Hello Ab
Problem that I'm facing:
In the above code I've satisfied all the rules and my code has matched the expected output. Even though it is showing error in the output screen.
Upvotes: 0
Views: 46