오늘의 키워드
•
문자열 처리
•
패턴 매칭
•
부분 문자열 비교
문제 파악 및 풀이
•
문제를 보자마자 패턴 length()를 활용해 substring과 equals로 앞뒤를 비교하면 되겠다고 생각했다.
•
입력된 패턴을 기준으로 나누어 앞부분(startPattern)과 뒷부분(endPattern)을 저장했다.
•
이후 각 문자열에 대해 앞부분과 뒷부분이 각각 일치하는지를 확인해 "DA" 또는 "NE"를 출력하는 방식으로 풀었다.
Java 풀이
import java.io.*;
import java.util.*;
class Main {
public static final int MAX_N = 100;
public static int n;
public static String pattern = "", startPattern = "", endPattern = "";
public static int startLength, endLength;
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
init();
while (n-- > 0) {
boolean matchStart = false;
boolean endStart = false;
String input = br.readLine();
int inputLength = input.length();
if (inputLength >= startLength + endLength) {
matchStart = input.substring(0, startLength).equals(startPattern);
endStart = input.substring(inputLength - endLength).equals(endPattern);
}
if (matchStart && endStart) {
System.out.println("DA");
} else {
System.out.println("NE");
}
}
}
public static void init() throws IOException {
n = Integer.parseInt(br.readLine());
pattern = br.readLine();
boolean isStartPattern = true;
for (int i = 0; i < pattern.length(); i++) {
if (pattern.charAt(i) == '*') {
isStartPattern = false;
continue;
}
if (isStartPattern) {
startPattern += pattern.charAt(i);
} else {
endPattern += pattern.charAt(i);
}
}
startLength = startPattern.length();
endLength = endPattern.length();
}
}
Java
복사
1년 전 Python 풀이 (가독성 및 시간 복잡도 측면에서 우수)
N = int(input())
P = input().split('*')
for _ in range(N):
fileName = input()
ans = True
if not P[0] == fileName[:len(P[0])]:
ans = False
if not fileName[len(P[0]):].endswith(P[1]):
ans = False
if ans:
print('DA')
else:
print('NE')
Python
복사
시간 복잡도
•
O(N × L)
(N: 파일 이름의 개수, L: 파일 이름의 최대 길이)
각 파일 이름에 대해 부분 문자열 비교를 두 번 진행하는 방식이기 때문에, 전체 시간 복잡도는 O(N × L) 이다.
오늘의 회고
어려웠던 점
•
문제를 풀 당시에는 substring과 equals를 활용해 직접 비교하는 방식을 사용했다.
•
풀이 자체는 맞았지만, 자바 String 메서드(특히 startsWith, endsWith)를 활용하는 더 간결하고 직관적인 방법을 떠올리지 못한 점이 아쉬웠다.
개선점
•
1년 전 파이썬 풀이를 다시 보니 split('*')로 패턴을 나누고, startswith, endswith를 활용한 방식이 훨씬 깔끔했다.
•
자바에서도 startsWith, endsWith 메서드를 적극적으로 사용할 수 있었는데, 문자열 메서드에 대한 이해 부족으로 단순 비교 방식만 고수했다.
•
앞으로는 문제를 풀고 난 뒤, 표준 라이브러리 함수들을 적극 활용할 수 있는지 다시 점검하는 습관을 들이자.