-
32. 괄호 변환코딩 테스트/Level 2 2020. 8. 16. 13:20반응형
https://programmers.co.kr/learn/courses/30/lessons/60058
괄호 변환
2020 KAKAO BLIND RECRUITMENT
2862명 완료얼추 복잡해 보이지만 시키는 데로 코딩하면 끝
괄호 체크에 대해선 예전에 블로그에 올린 글 참고..
def solution(p): if p == '': return '' left, right, balance = 0, 0, 0 for i, v in enumerate(p): if v == '(': left += 1 else: right += 1 if left == right: balance = i break u = p[:balance + 1] v = p[balance + 1:] if check(u): return u + solution(v) else: temp = "" for each in u[1:-1]: temp += ')' if (each == '(') else '(' return '(' + solution(v) + ')' + temp def check(text): stack = [] for each in text: if each == '(': stack.append('(') else: if stack: stack.pop() else: return False return True
java
import java.util.ArrayList; class Solution { boolean check(String s) { var stack = new ArrayList<Character>(); for (var each : s.toCharArray()) { if (each == '(') { stack.add('('); } else { if (stack.size() > 0) stack.remove(stack.size() - 1); else return false; } } return true; } public String solution(String p) { if (p.length() == 0) return ""; int left = 0, right = 0, balance = 0; for (var i = 0; i < p.length(); i++) { if (p.charAt(i) == '(') left++; else right++; if (left == right) { balance = i; break; } } var u = p.substring(0, balance + 1); var v = p.substring(balance + 1); if (check(u)) { return u + solution(v); } else { StringBuilder temp = new StringBuilder(); for (var each : u.substring(1, u.length() - 1).toCharArray()) { temp.append(each == '(' ? ')' : '('); } return '(' + solution(v) + ')' + temp; } } }
반응형