From the course: Programming Foundations: Data Structures

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Solution: Matching parentheses

Solution: Matching parentheses

- [Instructor] Let's write a function that checks whether a string has matching parentheses. To keep track of whether we've seen an opening parentheses or not, we'll use a stack in the form of a deck. Then we'll iterate through the string. If we see a character that's an opening parentheses, we'll add it to the stack. If we come across a closing parentheses, we'll need to check if there's an opening parentheses to match it. We can do this by popping off an item from the stack. Of course, we'll need to ensure that the stack isn't empty. If it is, that means we found a closing parentheses before any opening one, meaning the parentheses are imbalanced. In that case, we should return false immediately. If the stack does have items, we'll pop one off to complete the match. After iterating through the entire string that the stack is empty, this means that every opening parentheses had a closing parentheses. If there are still items in the stack, it means there are unmatched opening…

Contents