From 8b77c71b55d811268c978dc34cedba8524cf7a8f Mon Sep 17 00:00:00 2001 From: Ben Date: Fri, 29 May 2026 15:14:48 +0100 Subject: [PATCH] solve duplicate word problem --- Java/2_JavaRegex.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Java/2_JavaRegex.java diff --git a/Java/2_JavaRegex.java b/Java/2_JavaRegex.java new file mode 100644 index 0000000..5232606 --- /dev/null +++ b/Java/2_JavaRegex.java @@ -0,0 +1,28 @@ +public class 2_JavaRegex { + //Name:Benjamen Folarin + //Date:5/29/2026 + + 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(); + } +} \ No newline at end of file