코테 문제풀이 3일차

아빠는 외계연·2022년 12월 21일
0

CodingTest

목록 보기
4/18

👑문제: [프로그래머스 Level2]

2020 KAKAO BLIND RECRUITMENT > 괄호 변환

문제 시 고려해야 할 점


이 설명만 따라가면 충분히 풀 수 있는 문제

풀이 과정

import java.util.*;
class Solution {
    static public int checkBalance(String str) {
        int open = 0, close = 0, split = -1;
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == '(') open++;
            else close++;

            if(open == close) {
                split = i;
                return split;
            }
        }
        return split;
    }
    static public boolean checkRight(String str) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i) == '(') {
                stack.push('(');
            }
            else {
                if(stack.isEmpty()) return false;
                else stack.pop();
            }
        }
        if(!stack.isEmpty())return false;
        return true;
    }
    static public String check(String str) {
        //step1
        if(str.equals("")) return str;

        //step2
        int split = checkBalance(str);
        String u = str.substring(0,split+1);
        String v = str.substring(split+1,str.length());

        //step3
        if(checkRight(u)) return u + check(v);
        else {
            String newU = u.substring(1,u.length()-1);
            String tmp = "";
            for (int i = 0; i < newU.length(); i++) {
                if(newU.charAt(i) == '(') tmp+=')';
                else tmp+='(';
            }
            return '(' + check(v) + ')' + tmp;
        }
    }
    public String solution(String p) {
        return check(p);
    }
}

느낀점

코드 실행하면 스택오버플로우 에러가 나고 그냥 체점하면 다 통과된다..? 먼가 이상한 문제

profile
Backend Developer

0개의 댓글