File tree Expand file tree Collapse file tree
src/programmers/level2/week_18 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package programmers .level2 .week_18 ;
2+
3+ import java .util .Stack ;
4+
5+ /**
6+ * 짝지어 제거하기
7+ * https://programmers.co.kr/learn/courses/30/lessons/12973?language=java
8+ */
9+ public class Solution001 {
10+ public static void main (String [] args ) {
11+ Solution001 sol = new Solution001 ();
12+ System .out .println (sol .solution ("baabaa" ));
13+ }
14+
15+ public int solution (String s ) {
16+ Stack <Character > stack = new Stack <>();
17+
18+ for (int i = 0 ; i < s .length (); i ++) {
19+ char c = s .charAt (i );
20+ if (!stack .isEmpty () && stack .peek () == c ) {
21+ stack .pop ();
22+ continue ;
23+ }
24+ stack .push (c );
25+ }
26+
27+ return stack .size () == 0 ? 1 : 0 ;
28+ }
29+ }
Original file line number Diff line number Diff line change 1+ package programmers .level2 .week_18 ;
2+
3+ /**
4+ * 괄호 변환 https://programmers.co.kr/learn/courses/30/lessons/60058?language=java
5+ */
6+ public class Solution002 {
7+ public static void main (String [] args ) {
8+ Solution002 sol = new Solution002 ();
9+ System .out .println (sol .solution ("()))((()" ));
10+ }
11+
12+ public String solution (String p ) {
13+ StringBuilder sb = new StringBuilder ();
14+ if (p .length () == 0 ) {
15+ return sb .toString ();
16+ }
17+
18+ String u = null ;
19+ String v = null ;
20+ int cnt = p .charAt (0 ) == '(' ? 1 : -1 ;
21+ for (int i = 1 ; i < p .length (); i ++) {
22+ if (p .charAt (i ) == '(' ) {
23+ cnt ++;
24+ } else {
25+ cnt --;
26+ }
27+
28+ if (cnt == 0 ) {
29+ u = p .substring (0 , i + 1 );
30+ v = p .substring (i + 1 );
31+ break ;
32+ }
33+ }
34+
35+ if (isRight (u )) {
36+ sb .append (u );
37+ sb .append (solution (v ));
38+ } else {
39+ sb .append ("(" + solution (v ) + ")" );
40+ for (int i = 1 ; i < u .length () - 1 ; i ++) {
41+ if (u .charAt (i ) == '(' )
42+ sb .append (')' );
43+ if (u .charAt (i ) == ')' )
44+ sb .append ('(' );
45+ }
46+ }
47+
48+ return sb .toString ();
49+ }
50+
51+ public boolean isRight (String s ) {
52+ int cnt = 0 ;
53+ for (int i = 0 ; i < s .length (); i ++) {
54+ if (s .charAt (i ) == '(' ) {
55+ cnt ++;
56+ } else {
57+ cnt --;
58+ }
59+
60+ if (cnt < 0 ) {
61+ return false ;
62+ }
63+ }
64+ return true ;
65+ }
66+ }
You can’t perform that action at this time.
0 commit comments