반응형
해커랭크-자바 정규표현2:https://www.hackerrank.com/challenges/duplicate-word/problem?isFullScreen=true
Java Regex 2 - Duplicate Words | HackerRank
Identify repeated words in the sentence, and delete all recurrences of each word after the very first word.
www.hackerrank.com
문제설명
이하의 세 조건을 만족할 것.
- 반복되는 단어와 일치하는 정규표현식을 작성할 것.
- 대소문자를 구분하지 않도록 두번째 컴파일 인수를 작성할 것.
- 문장안에서 발견된 반복되는 단어 중 첫 번째 단어로 대체되도록 replaceAll의 두가지 인수를 작성할 것.
입출력 예
Input
입력된 첫 라인은 정수로, 이후 입력될 라인의 수를 의미합니다.
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
Goodbye bye world
Sam went to his business
Reya is the best player in eye game
in inthe
Hello Ab
풀이
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class post {
public static void main(String[] args) {
String regex = "\\b(\\w+)(?:\\W+\\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();
}
}
먼저 정규표현식을 설명하겠습니다.
표현식 | 설명 |
\b | word boundary를 의미. 문자와 공백사이의 문자. |
(\w+) | 반복되는 단어를 의미. 이 그룹은 단어의 첫번째 항목을 캡쳐한다. |
(?:\W+\1\b)+ | 괄호안의 조건을 일치하는 논 캡쳐 그룹. +가 있으므로 반복되는 그룹을 뜻한다. |
\W+ | 반복되는 비 단어를 의미한다. 이 문제에서는 공백에 해당 될 것이다. |
\1 | 캡쳐된 첫번째 그룹(\w+)을 의미한다. |
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
두번째 인수에 오는 CASE_INSENSITIVE는 소문자 대문자 구분없이 매칭하도록 설정합니다.
input = input.replaceAll(m.group(), m.group(1));
상기의 정규식으로 매칭된 그룹 중 첫번째 그룹으로 replace하도록 합니다.
반응형
'코딩테스트 > HackerRank' 카테고리의 다른 글
HackerRank~BigDecimal (0) | 2023.07.30 |
---|---|
HackerRank~Tag Content Extractor (0) | 2023.07.08 |
HackerRank~Java Regex (0) | 2023.06.22 |
HackerRank~Java Loop2 (0) | 2023.06.16 |