Lab 3: Matching Parenthesis
Objective
To be able to utilize stacks in a Java program.
Task
For this lab, you will write a program that checks whether a string of parentheses and brackets is well-formed or not. The strings will be considered well-formed if each opening parenthesis/bracket is matched with exactly one closing parenthesis/bracket.
For example, the following strings are well-formed:
- ([()])
- ()[]()
- (([]([])))
While the following are not:
- )(
- (]
- []]
- [[]
- (()[]([[])]]
This problem is best solved with a stack. The basic idea is to store the opening symbols on a stack. When you see a closing symbol, pop off the next opening symbol and make sure it matches. When done, ensure the stack is empty.
Details
- You can use the Java Stack class for this lab (which happens to be array-based). Make it a stack of characters.
- Read in one String from the user.
- Loop through the characters of the String.
- Follow the algorithm outlined above.
- At the end, print whether the String is well-formed or not.
- Be sure to test different cases!
Submitting
When you're finished, please submit your code for this lab on Canvas.