s
λ μ¬λ¬ κ΄νΈλ€λ‘ μ΄λ£¨μ΄μ§ string
μΈμλ€.
s
κ° μ ν¨ν ννμΈμ§ μλμ§ True/False
λ‘ λ°ννλΌ
μ’
λ₯λ ' ( ', ' ) ', ' [ ', ' ] ', ' { ', ' } ' μΌλ‘
μ΄ 6κ° μλ€.
ν λ² κ΄νΈλ₯Ό μμνμΌλ©΄, κ°μ κ΄νΈλ‘ λλ΄μΌ νλ€.
κ΄νΈ μμκ° λ§μμΌ νλ€.
𧡠μμ)
s = '()' return True
s = '()[]{}' return True
s = '(]' return False
s = '([)]' return False
s='{()}' return True
def is_valid(string):
#step1
symbols = {
'(' : -1, ')' : 1,
'{' : -2, '}' : 2,
'[' : -3, ']' : 3
}
x=[]
#step2
for i in range(len(string)):
x.append(string[i])
#step3
if len(symbols) >= 2 and symbols[x[-2]]<0 and symbols[x[-2]] + symbols[x[-1]] == 0:
x.pop()
x.pop()
return len(x) == 0
string
μμ λ°μ λ¬Έμλ₯Ό λ°°μ΄μ μ μ₯νλ€.
κ°κ°μ κ΄νΈμ μ«μλ₯Ό λμ μμΌ κ΄νΈ μμ΄ μλ‘ λ§μΌλ©΄,
κ·Έ μμ λ°°μ΄μμ μ κ±°νλ μ°μ°μ λ°λ³΅ν΄μ
λ§μ½, x
μ λ¨μ μμκ° μμΌλ©΄ True
λ€ μ κ±°λμ§ μμΌλ©΄, False
λ₯Ό λ°ν νλ€.
def is_valid(string):
#step1
symbols = {
'(' : -1, ')' : 1,
'{' : -2, '}' : 2,
'[' : -3, ']' : 3
}
x=[]
symbols
λΌλ dictionary
λ₯Ό ν΅ν΄ κ΄νΈμ μ«μλ₯Ό λμ μν¨λ€. string
μ ν κΈμμ© λ΄μ x
리μ€νΈλ₯Ό μμ± νλ€.
def is_valid(string):
#... ...#
#step2
for i in range(len(string)):
x.append(string[i])
if len(symbols) >= 2 and symbols[x[-2]] < 0 and symbols[x[-2]] + symbols[x[-1]] == 0:
x.pop()
x.pop()
return len(x) == 0
x
μ string
ν κΈμμ© λ΄μ, x
μ λ§μ§λ§ λ μμκ° λ κ΄νΈ μμΌλ‘ λμνλ©΄ 리μ€νΈμμ μ κ±° νλ€.
리μ€νΈμ λ¨μ μλ κ²μ΄ μμΌλ©΄, True
리μ€νΈμ λ¨μ μλ κ²μ΄ μμΌλ©΄, False
λ₯Ό
λ°ννλ€.