문제링크 : https://programmers.co.kr/learn/courses/30/lessons/60058
코딩테스트 연습 - 괄호 변환
카카오에 신입 개발자로 입사한 콘은 선배 개발자로부터 개발역량 강화를 위해 다른 개발자가 작성한 소스 코드를 분석하여 문제점을 발견하고 수정하라는 업무 과제를 받았습니다. 소스를 컴�
programmers.co.kr
문제설명
균형잡힌 괄호 문자열 p가 매개변수로 주어질 때, 주어진 알고리즘을 수행해 올바른 괄호 문자열로 변환한 결과를 return 하도록 solution 함수를 완성해 주세요.
알고리즘
1. 문자열 u를 먼저 알고리즘에 맞게 구하고
2. 문자열 v를 u ,v 로 다시나누는 과정을 재귀적으로 구현.
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
#괄호 변환
def return_uv(s):
for idx in range(1,len(s),2):
a=0
b=0
uu=''
vv=''
for c in s[0:idx+1]:
if c==')': a+=1
else : b+=1
if a==b :
uu = s[0:idx+1]
vv = s[idx+1:]
break
return [uu,vv]
def check_collect(s):
test = []
test.append(s[0])
for idx in range(1,len(s)):
if s[idx]==')':
if(test[-1]=='('):
test.pop(-1)
else :test.append(s[idx])
if len(test)==0:
return True
else:
return False
def change(s) :
s = s[1:-1]
re =''
for c in s:
if c=='(':re+=')'
else :re+='('
return re
def solution(p):
if p=='':
return ""
List = return_uv(p)
u = List[0]
v = List[1]
if check_collect(u):
return u + str(solution(v))
else :
return '(' + str(solution(v)) + ')'+str(change(u))
|
cs |
'파이썬 > 프로그래머스' 카테고리의 다른 글
[python] 프로그래머스 - 수식 최대화 (0) | 2020.08.04 |
---|---|
[python] 프로그래머스 - 튜플 (0) | 2020.08.04 |
[python] 프로글래머스 - 멀쩡한 사각형 (0) | 2020.08.04 |
[python] 프로그래머스 - 실패율 (0) | 2020.08.04 |
[python] 프로그래머스 - 키패드 누르기 (0) | 2020.08.04 |