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);
}
}
코드 실행하면 스택오버플로우 에러가 나고 그냥 체점하면 다 통과된다..? 먼가 이상한 문제