A stack matches things that open and close, such as brackets in a program. Each opening bracket is pushed, and each closing bracket pops one: it fails if there is nothing to pop.
What to build
Read a line of brackets ( and ), and print yes if they are balanced, or no if not.
Requirements
- Every
)must match an earlier(, and every(must be closed. - An empty line is balanced.
- Use the stack to hold the open brackets.
Input
A line of 0 to 30 characters, each ( or ), then Enter.
Output
yes or no.
Constraints
Only ( and ) appear in the line.
Example
Input:
(()())
Output:
yes
Why it works
Each ( is pushed as a pending bracket, and each ) removes the most recent one, which is the one it closes. A ) that finds the stack empty has no partner, so the answer is no at once. If the line ends and something is still on the stack, a bracket was never closed, so the answer is no then too.
Examples
(()())
yes
())(
no
Hints
Hint 1
Keep the depth in BX. For '(' PUSH AX and INC BX. For ')' check BX first: if it is 0 the brackets are not balanced; otherwise POP AX and DEC BX.
Hint 2
Read keys with AH = 1 until Enter (0Dh). The line has only '(' and ')'.
Hint 3
At the end, the brackets are balanced when no ')' came too early and BX is 0. Print `yes` or `no`.
Solution
Show one correct solution (try it yourself first)
; Balanced brackets
.MODEL SMALL
.STACK 100H
.DATA
YES DB 'yes$'
NO DB 'no$'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
MOV BX, 0 ; the number of open brackets
READ:
MOV AH, 1
INT 21H
CMP AL, 0DH
JE END_OF_LINE
CMP AL, '('
JNE CLOSING
PUSH AX
INC BX
JMP READ
CLOSING:
CMP BX, 0
JE BAD ; a ')' with nothing to close
POP AX
DEC BX
JMP READ
END_OF_LINE:
CMP BX, 0
JNE BAD
LEA DX, YES
JMP SHOW
BAD:
LEA DX, NO
SHOW:
MOV AH, 9
INT 21H
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step