From 56b78a24057653afd57360ebe49acb99a5f17fb0 Mon Sep 17 00:00:00 2001 From: AMIT KUMAR <130446160+AMITKUMAR6549@users.noreply.github.com> Date: Sun, 20 Aug 2023 03:16:01 +0530 Subject: [PATCH] Update JavaRegex2.java Refactored DuplicateWords Java program for readability and efficiency. - Improved code formatting and indentation. - Employed more descriptive variable names. - Enhanced duplicate word removal logic for efficiency. - Adhered to consistent Java coding conventions. --- Java/Strings/JavaRegex2.java | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/Java/Strings/JavaRegex2.java b/Java/Strings/JavaRegex2.java index c1d3eaf..f5ca085 100644 --- a/Java/Strings/JavaRegex2.java +++ b/Java/Strings/JavaRegex2.java @@ -42,31 +42,34 @@ in inthe */ - import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class JavaRegex2 -{ - public static void main(String[] args){ +public class DuplicateWords { + + public static void main(String[] args) { - String pattern = "(?i)\\b(\\w+)(\\s+\\1)+\\b"; - Pattern r = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); + String regex = "\\b(\\w+)(\\s\\1)+\\b"; + Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Scanner in = new Scanner(System.in); - int testCases = Integer.parseInt(in.nextLine()); - while(testCases>0){ + int numSentences = Integer.parseInt(in.nextLine()); + + while (numSentences-- > 0) { String input = in.nextLine(); - Matcher m = r.matcher(input); - boolean findMatch = true; - while(m.find( )){ - input = input.replaceAll(pattern,"$1"); - findMatch = false; + + 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); - testCases--; } + + in.close(); } } -