sλ μ¬λ¬ κ΄νΈλ€λ‘ μ΄λ£¨μ΄μ§ string μΈμλ€.
sκ° μ ν¨ν ννμΈμ§ μλμ§ True/Falseλ‘ λ°ννλΌ
μ’
λ₯λ ' ( ', ' ) ', ' [ ', ' ] ', ' { ', ' } ' μΌλ‘
μ΄ 6κ° μλ€.
ν λ² κ΄νΈλ₯Ό μμνμΌλ©΄, κ°μ κ΄νΈλ‘ λλ΄μΌ νλ€.
κ΄νΈ μμκ° λ§μμΌ νλ€.
π§΅ μμ)
s = '()' return Trues = '()[]{}' return Trues = '(]' return Falses = '([)]' return Falses='{()}' 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λ₯Ό
λ°ννλ€.