기억은 짧고 기록은 길다
[프로그래머스/Programmers] 괄호 변환 - Python 본문
Link
코딩테스트 연습 - 괄호 변환
카카오에 신입 개발자로 입사한 "콘"은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코드를 분석하여 문제점을 발견하고 수정하라는 업무 과제를 받았습니다. 소스를
programmers.co.kr
Solution
def isBalanced(s):
return s.count('(') == s.count(')')
def isCorrect(s):
if s[0] == ')':
return False
count = 0
for i in range(len(s)):
if s[i] == '(':
count += 1
else:
count -= 1
if count < 0:
return False
return count == 0
def solution(p):
answer = ''
u = ''
v = ''
if len(p) == 0 or isCorrect(p):
return p
for i in range(2, len(p) + 1, 2):
if isBalanced(p[0:i]):
u = p[0:i]
v = p[i:]
break
if isCorrect(u):
answer += u + solution(v)
else:
answer += '(' + solution(v) + ')'
for c in u[1:-1]:
if c == '(':
answer += ')'
else:
answer += '('
return answer
return p
Other Solution
def solution(p):
if p == '':
return p
chk = True
count = 0
for i in range(len(p)):
if p[i] == '(':
count += 1
else:
count -= 1
if count < 0:
chk = False
if count == 0:
if chk:
return p[:i+1] + solution(p[i + 1:])
else:
return '(' + solution(p[i + 1:]) + ')' + ''.join(list(map(lambda x: '(' if x == ')' else ')', p[1:i])))'CodingTest > programmers' 카테고리의 다른 글
| [프로그래머스/Programmers] JadenCase 문자열 만들기 - Python (0) | 2021.10.04 |
|---|---|
| [프로그래머스/Programmers] 큰 수 만들기 - Python (0) | 2021.10.03 |
| [프로그래머스/Programmers] 피보나치 수 - Python (0) | 2021.09.23 |
| [프로그래머스/Programmers] 타겟 넘버 - Python (0) | 2021.09.23 |
| [프로그래머스/Programmers] 튜플 - Python (0) | 2021.09.22 |
Comments