2019. 4. 1. 23:17ㆍ알고리즘문제/Hackerrank
Pattern 클래스가 뭘까 정말 어렵다.
정규표현을 확인할 때 사용되는 건 알겠는데 어렵다.
정확히 어떤 클래스인지 아시는 분 댓글 부탁드려요 ㅜㅜ!!!!
정의
java.lang.Object
- java.util.regex.Pattern
일단 Java Doc을 참고하면
" A compiled representation of a regular expression "
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.
이렇게 Pattern이 정의되어 있다.
오로지 정규표현식을 compile 하기 위한 클래스인가 ??? !!
정의처럼 Pattern 클래스는 compile 메소드를 가장 많이 사용한다.
Method
- compile : 주어진 flags 조건대로 정규표현식(regex)를 컴파일한 후 Pattern클래스를 반환한다.
Pattern p = Pattern.compile(regex, flags);
* 여기서 컴파일의 의미는 ? 잘 모르겠다.
* flags 의 종류로는 CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL and COMMENTS 가 있다.
- matcher : 패턴과 함께 input값을 매치하는 Matcher객체(정규표현엔진)를 만들어 반환한다.
Matcher m = p.matcher(charSequence input);
- matches : 주어진 입력 문자에서 특별한 패턴을 빠르게 체크한다.
Pattern.matches(String regex, CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.
* Matcher객체의 matches 메소드도 따로 있다.
ex) boolean b = m.matches();
주어진 패턴과 input값이 매치하는지 확인 후 결과 값을 논리형으로 반환한다.
문제
반복된 단어를 하나로 만들어 문장을 완성시켜라.
ex) input : 1
Hello heLLo heLlo Im iM dadee !
output : Hello Im dadee !
위의 정수 1은 입력 스트링의 갯수를 의미한다. 정수가 3으로 주어진다면 입력 스트링과 출력 스트링은 3개가 될 것 !
역시나 Discussion에 천재적인 친구가 있었다.
그의 풀이 !
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateWords {
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();
}
}
풀이
* Regex : "\b(\w+)(?:\W+\1\b)+"
\b : 단어 경계
\w : [a-zA-Z_0-9] 알파벳과 숫자, 그리고 _(언더바)를 찾음
\W : [^\w] 알파벳과 숫자, 그리고 _(언더바)가 아닌 것을 찾음
\1 : 부모 중 첫번째 그룹과 매치되는 것이 와라 !
+ : 앞 문자가 1개 혹은 그 이상임
? : 앞 문자가 없거나 하나 있음
*Groups
input = input.replaceAll(m.group(), m.group(1));
전체 그룹들을 기준 그룹으로 바꿔랑.
*m.find()
Attempts to find the next subsequence of the input sequence that matches the pattern.
참조
- flags 종류 설명
http://egloos.zum.com/ultteky/v/3945804
- 그가 참고했다던 링크
http://tutorials.jenkov.com/java-regex/matcher.html
- 정규식으로 특정문자 제거하기
'알고리즘문제 > Hackerrank' 카테고리의 다른 글
자바_이진검색트리(Binary Search Trees) (0) | 2019.04.18 |
---|---|
Minimum Operation (0) | 2019.04.03 |
자바_정규표현식(matches, pattern) (0) | 2019.04.01 |
자바 SortedSet, TreeSet (0) | 2019.03.29 |
자바(Java)_Arrays.sort 메소드 활용 (0) | 2019.03.27 |