ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Programmers] 괄호 변환
    Algorithm/Programmers 2020. 6. 2. 16:13

    [Level 2] 괄호 변환

    https://programmers.co.kr/learn/courses/30/lessons/60058

     

     

     

    Solution

    • 문제에서 주어진 조건대로 재귀 함수로 구현하여 풀 수 있었다.

     

     

    소스코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    import java.util.*;
    class Solution {  
        static StringBuilder sb;
        public String solution(String p) {
            String answer = "";
            return recursive(p);   
        }
        
        public static boolean isCorrect(String s){
            int count = 0;
            for(int i = 0; i<s.length(); i++){
                if(s.charAt(i) == '(')
                    count++;
                else
                    count--;
                if(count <0 ) return false;
            }
            return true;
        }
        public static String recursive(String w){
            if(w.equals("")) return "";
             String u = devide(w);
             String v = w.substring(u.length(), w.length());
            if(isCorrect(u)){
                return u + recursive(v);
            }else{
               String temp = "(" + recursive(v) + ")";
                u = u.substring(1, u.length()-1);
                sb = new StringBuilder();
                for(int i = 0; i<u.length(); i++){
                    if(u.charAt(i) == '(')
                        sb.append(")");
                    else
                        sb.append("(");
                }
               return temp + sb.toString();
            }
        }
        
        public static String devide(String p){
            sb = new StringBuilder();
            int open = 0, close = 0;
            for(int i = 0; i< p.length();i++){
                if(p.charAt(i) == '('){
                    open++;
                    sb.append("(");
                }else{
                    close++;
                    sb.append(")");
                }
                
                if(open == close){
                   break;
                }
            }
            return sb.toString();
        }
    }
    cs

    'Algorithm > Programmers' 카테고리의 다른 글

    [Programmers] 카카오프렌즈 컬러링북  (0) 2020.06.16
    [Programmers] 라면공장  (0) 2020.06.04
    [Programmers] 전화번호 목록  (0) 2020.06.01
    [Programmers] 멀쩡한 사각형  (0) 2020.06.01
    [Programmers] 가장 큰 수  (0) 2020.05.31

    댓글

Designed by Tistory.