Question
Java Use Stack class to match balanced parentheses and brackets. Create a class, with a method: public static boolean matchParentheses(String s); It takes a String
Java
Use Stack class to match balanced parentheses and brackets. Create a class, with a method:
public static boolean matchParentheses(String s); It takes a String containing (, ), [, and ] and returns true if the parentheses are balanced.
For example: Matcher.matchParentheses("()") // returns true
Matcher.matchParentheses("([])") // returns true
Matcher.matchParentheses("([])[()]") // returns true
Matcher.matchParentheses("([)]") // returns false
Matcher.matchParentheses("(") // returns false
Matcher.matchParentheses("[]]") // returns false
I suggest implementing this by using Stack, pushing a ( or [ onto the stack whenever one of those characters is seen, and popping it off when the corresponding closing character is seen. If the wrong character is at the top of the stack, the parentheses do not match, and the method should return false. Note that Stack class can hold Character objects, but not char values, since char is a primitive type.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started