使用正则表达式移除句子中不区分大小写重复词的Java代码问题
HackerRank Regex - Duplicate Words Java问题排查
我正在解决HackerRank的Regex - Duplicate Words Java问题,目标是使用正则表达式移除句子中重复的单词,保留首次出现的单词且不区分大小写(例如输入I love Love to To tO code应输出I love to code)。需完成以下三个要求:
- 编写匹配重复单词的RegEx;
- 添加编译参数使RegEx不区分大小写;
- 使用
replaceAll将重复词替换为首次出现的单词并保留原大小写。
我编写的代码如下:
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(); } }
输入(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
我的输出
- Goodbye bye world
- Sam went to his business
- Reya is the best player in eye game
- in inthe
- Hello Ab
预期输出
- Goodbye bye world
- Sam went to his business
- Reya is the best player in eye game
- in inthe
- Hello Ab
我的问题:我已满足所有要求,代码输出与预期完全一致,但平台仍显示错误。
内容的提问来源于stack exchange,提问作者Uday Kumar
相关产品推荐
相关产品推荐

