Algoritme & struktura të dhënash

Balanced parentheses

Në shqip: Kllapat e balancuara

ShpjegimiSQ

A janë kllapat ( [ { të mbyllura saktë? Me një stivë: çdo kllapë hapëse e fut, çdo mbyllëse duhet të përputhet me majën. Kështu e kontrollojnë editorët dhe kompajlerët kodin.

EnglishEN

Are the brackets ( [ { closed correctly? With a stack: push every opening bracket; every closing one must match the top. That's how editors and compilers check code.

Si ta mendosh

Si kukullat ruse: e fundit që hape duhet të mbyllet e para.

Lexoje në anglisht

Like Russian dolls: the last one you opened must close first.

Shembull kodipython

stiva, ciftet = [], {")": "(", "]": "[", "}": "{"}
for c in s:
    if c in "([{": stiva.append(c)
    elif c in ciftet and (not stiva or stiva.pop() != ciftet[c]): print(False); break
else: print(not stiva)

Terma të lidhur