File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ 최대건수가 20만건이기 때문에 O(n)안에 끝내야 한다.
2+
3+ ~~~ java
4+ import java.io.BufferedReader ;
5+ import java.io.InputStreamReader ;
6+ import java.time.LocalDate ;
7+ import java.util.* ;
8+
9+
10+ class Main {
11+ public static void main (String [] args ) throws Exception {
12+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
13+ int n = Integer . parseInt(br. readLine());
14+ String s = br. readLine();
15+
16+ Deque<Integer > stack = new ArrayDeque<> ();
17+ int maxLength = 0 ;
18+
19+ // 초기 인덱스를 스택에 추가하지 않음
20+ for (int i = 0 ; i < s. length(); i++ ) {
21+ if (s. charAt(i) == ' (' ) {
22+ stack. push(i); // 여는 괄호의 인덱스를 스택에 추가
23+ } else {
24+ if (! stack. isEmpty() && s. charAt(stack. peek()) == ' (' ) {
25+ stack. pop(); // 올바른 쌍을 만난 경우 스택에서 제거
26+ int lastValidIndex = stack. isEmpty() ? - 1 : stack. peek();
27+ maxLength = Math . max(maxLength, i - lastValidIndex);
28+ } else {
29+ stack. push(i); // 닫는 괄호이지만 스택이 비어있거나 짝이 맞지 않는 경우 인덱스를 추가
30+ }
31+ }
32+ }
33+ System . out. println(maxLength);
34+ }
35+ }
36+ ~~~
You can’t perform that action at this time.
0 commit comments