Question: Complete the method so that the program can determine whether a string that contains (, ), [, ], {, and } are properly nested. Note
Complete the method so that the program can determine whether a string that contains (, ), [, ], {, and } are properly nested. Note that ( and ) match each other as a pair, [ and ] are a pair, and { and } are a pair. All other characters should be ignored.
For example:
{[()]()} is nested properly: true {a+[b*(10+10)]*(c-d)} is nested properly: true ([()]{} is nested properly: false (a+[b*(e-f)]-{a+b} is nested properly: false [{}]()]() is nested properly: false [{)]() is nested properly: false [{})() is nested properly: false
(z+s)*[c-d]/{a+t} is nested properly: true
Starter code///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class ParenthesesBracketsMatch { public static boolean AreParenthesesBracketsNested(String str) { // Create a stack java.util.Stack public static void main(String[] args) { //DO NOT CHANGE THE MAIN METHOD String str1 = "{[()]()}"; boolean matched1 = AreParenthesesBracketsNested(str1); System.out.println(str1 + " is nested properly: " + matched1); String str1b = "{a+[b*(10+10)]*(c-d)}"; boolean matched1b = AreParenthesesBracketsNested(str1b); System.out.println(str1b + " is nested properly: " + matched1b); String str2 = "([()]{}"; boolean matched2 = AreParenthesesBracketsNested(str2); System.out.println(str2 + " is nested properly: " + matched2); String str2b = "(a+[b*(e-f)]-{a+b}"; boolean matched2b = AreParenthesesBracketsNested(str2b); System.out.println(str2b + " is nested properly: " + matched2b); String str3 = "[{}]()]()"; boolean matched3 = AreParenthesesBracketsNested(str3); System.out.println(str3 + " is nested properly: " + matched3); String str4 = "[{)]()"; boolean matched4 = AreParenthesesBracketsNested(str3); System.out.println(str4 + " is nested properly: " + matched4); String str5 = "[{})()"; boolean matched5 = AreParenthesesBracketsNested(str5); System.out.println(str5 + " is nested properly: " + matched5); String str6 = "(x+q)*[e-f]/{a+b}"; boolean matched6 = AreParenthesesBracketsNested(str6); System.out.println(str6 + " is nested properly: " + matched6); java.util.Scanner input = new java.util.Scanner(System.in); System.out.println("Enter a string of (, ), [, ], {, and }:"); String str = input.next(); boolean matched = AreParenthesesBracketsNested(str); System.out.println(str + " is nested properly: " + matched); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
