Ad space (banner)
๐ŸฆSwift Lessons
Lesson 63 / 68

Checking Balanced Parentheses (an Application of Stacks)

In this lesson you will learn how to check that brackets are balanced using a stack in Swift, a practical application of the stack data structure. This is for anyone searching for "Swift balanced parentheses stack".

With a stack (last in, first out) you can push opening brackets such as ( and [, then check each closing bracket against whatever is on top. That is how bracket matching works.

The sample code keeps the opening bracket for each closing bracket in the pairs dictionary, pushes with stack.append(ch) on an opening bracket, and checks the value from stack.removeLast() on a closing one. If the stack is empty once everything has been processed, the brackets are balanced.

A common stumbling block for beginners is handling several kinds of bracket at once (round, square, and curly mixed together). Counting openings and closings is not enough - you also have to confirm they nest in the right order.

The same idea is used behind editor auto-completion and code syntax checking. Plenty of similar tools check that HTML opening and closing tags line up correctly.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)