File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
AlgorithmDrills/src/Programmers Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ package Programmers ;
2+ import java .util .Stack ;
3+ public class No76502 {
4+ private boolean isCorrect (char [] str , int offset ) { //괄호들의 짝이 맞는지 확인하는 메서드
5+ Stack <Character > stack = new Stack <>();
6+
7+ for (int i = 0 ; i < str .length ; i ++) {
8+ char c = str [(offset + i ) % str .length ]; //offset은 시작 인덱스. 문자열 s에서 어느 위치부터 시작해서 괄호를 확인할지를 결정.
9+ switch (c ) {
10+ case '(' -> stack .push (')' ); // 여는 괄호를 만났을 때 닫는 괄호를 넣어준다.
11+ case '{' -> stack .push ('}' );
12+ case '[' -> stack .push (']' );
13+ case ')' , '}' , ']' -> { // 닫는 괄호를 만났을 때 스택의 가장 위에 있는 원소가 짝이 될 수 있는지 검사
14+ if (stack .isEmpty ()) return false ;
15+ if (stack .pop () != c ) return false ; // 스택 가장 위의 요소를 pop, 검사
16+ }
17+ }
18+ }
19+ return stack .isEmpty (); // 문자열 순회 후 모든 괄호의 짝이 맞으면 스택은 비어있을 것
20+ }
21+ public int solution (String s ) {
22+ char [] str = s .toCharArray ();
23+ int count = 0 ;
24+ for (int offset = 0 ; offset < str .length ; offset ++) { //
25+ if (isCorrect (str , offset )) {
26+ count ++;
27+ }
28+ }
29+ return count ;
30+ }
31+ }
You can’t perform that action at this time.
0 commit comments