Regex2 Duplicate Words HackerRank Solution

The program is designed to solve a common problem in text processing, which is the removal of duplicate words from sentences. The user inputs a number of sentences, and the program processes each sentence to remove any duplicate words. This is a common task in natural language processing and other areas where text data is handled.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Regex2 Duplicate Words HackerRank Solution HackerRank solution using CodeRankGPT:

The solution uses regular expressions (regex) to identify duplicate words in a sentence. The regex pattern '\b(\w+)(\b\W+\b\1\b)*' is used to match any word that is followed by itself. The Pattern and Matcher classes from the java.util.regex package are used to compile the regex pattern and match it against the input sentences. If a match is found, the duplicate word is removed using the replaceAll method. The process is repeated for each sentence input by the user.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.strings;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 */
public class JavaRegex2DuplicateWords {
	public static void main(String[] args) {

		String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";
		Pattern p = Pattern.compile(regex, Pattern.MULTILINE + 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();
	}
}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform