반응형
문제링크
https://programmers.co.kr/learn/courses/30/lessons/60058
코딩테스트 연습 - 괄호 변환
카카오에 신입 개발자로 입사한 "콘"은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코드를 분석하여 문제점을 발견하고 수정하라는 업무 과제를 받았습니다. 소스를
programmers.co.kr
소스
class Solution {
public String solution(String str) {
if ("".equals(str))
return "";
return split(str);
}
private String split(String str) {
int cnt = 0;
int idx = 0;
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '(')
--cnt;
else
++cnt;
if (cnt == 0) {
idx = i + 1;
break;
}
}
String u = str.substring(0, idx);
String v = str.substring(idx);
if (checkRight(u)) {
String result = solution(v);
return u + result;
} else {
String temp = "(";
temp += solution(v);
temp += ")";
temp += method4_4(u);
return temp;
}
}
private String method4_4(String u) {
String s = "";
for (int i = 1; i < u.length() - 1; ++i) {
if (u.charAt(i) == '(')
s += ")";
else
s += "(";
}
return s;
}
private boolean checkRight(String str) {
int cnt = 0;
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '(')
++cnt;
else
--cnt;
if (cnt < 0)
return false;
}
return true;
}
/**
* test
*/
public static void main(String[] args) {
System.out.println(new Solution().solution("()))((()"));
}
}
반응형
'개발 > 알고리즘' 카테고리의 다른 글
프로그래머스 압축 (0) | 2021.07.09 |
---|---|
프로그래머스 튜플 (0) | 2021.07.08 |
프로그래머스 최대공약수와 최소공배수 (0) | 2021.06.16 |
프로그래머스 핸드폰 번호 가리기 (0) | 2021.06.14 |
백준 2231 분해합 (0) | 2021.06.02 |
최근댓글