Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

hwooo

프로그래머스 (C/C++, Java) 60058 : 괄호 변환 본문

Study/Algorithm

프로그래머스 (C/C++, Java) 60058 : 괄호 변환

hwooo 2025. 1. 10. 02:00

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


풀이

문제에 주어진 방법대로 풀면 답을 구할 수 있다.


C/C++ 코드

#include <string>
#include <vector>

using namespace std;

bool checkCorrect(string u) {
    int openCnt = 0;
    for (int i = 0; i < u.length(); i++) {
        if (u[i] == '(') openCnt++;
        else openCnt--;
        if (openCnt < 0) return false;
    }
    if (openCnt != 0) return false;

    return true;
}

int getBalanceIdx(string u) {
    int open = 0, close = 0;
    for (int i = 0; i < u.length(); i++) {
        if (u[i] == '(') open++;
        else close++;
        if (open == close) return i + 1;
    }
    return u.length();
}

string getBalance(string w) {
    if (w.empty()) return "";

    int idx = getBalanceIdx(w);
    string u = w.substr(0, idx);
    string v = w.substr(idx);

    if (checkCorrect(u))
        return u + getBalance(v);    
    else {
        string s = "(" + getBalance(v) + ")";
        for (int i = 1; i < u.length() - 1; i++) {
            if (u[i] == '(') s.append(")");
            else s.append("(");
        }
        return s;
    }
}

string solution(string p) {
    return getBalance(p);
}

 

Java 코드

import java.util.*;

class Solution {
    public String solution(String p) {
        return getBalance(p);
    }
    
    private String getBalance(String w) {
        if (w.isEmpty()) return "";
        
        int idx = getBalanceIdx(w);
        String u = w.substring(0, idx);
        String v = w.substring(idx);
        
        if (checkCorrect(u))
            return u + getBalance(v);    
        else {
            StringBuilder sb = new StringBuilder();
            sb.append("(").append(getBalance(v)).append(")");
            for (int i = 1; i < u.length() - 1; i++) {
                if (u.charAt(i) == '(') sb.append(")");
                else sb.append("(");
            }
            return sb.toString();
        }
    }
    
    private int getBalanceIdx(String u) {
        int open = 0, close = 0;
        for (int i = 0; i < u.length(); i++) {
            if (u.charAt(i) == '(') open++;
            else close++;
            if (open == close) return i + 1;
        }
        return u.length();
    }
    
    private boolean checkCorrect(String u) {
        int openCnt = 0;
        for (int i = 0; i < u.length(); i++) {
            if (u.charAt(i) == '(') openCnt++;
            else openCnt--;
            if (openCnt < 0) return false;
        }
        if (openCnt != 0) return false;
        
        return true;
    }
}