Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are given a string consisting of parenthesis style characters () [] and {}.

ID: 3797952 • Letter: Y

Question

You are given a string consisting of parenthesis style characters () [] and {}. A string of this type is said to be correct if: (a) It is an empty string. (b) If string A is correct and string B is correct then string AB is correct. (c) If A is correct then (A), [A] and {A} are all correct. You are to write a program that takes as input from the keyboard a series of strings of this type that can be of any length. The first line of input will contain a single integer n telling you how many strings you will be testing. Following that integer will be n lines (each ending in a new-line character) that represent the strings you are supposed to test with one string per line. Your program should output Yes if a given string is correct and No otherwise. For example if the user types the following as input 3 ([]) (([{}]))) ([()[]]) () Then your program should give the following output: Yes No Yes You will note that if you do your program correctly there is no prompt for data and the yes and no answers will be interspersed with your input data when you enter it manually. The following would be a more accurate representation of what you see on the screen when you cut and paste the input into your program. 3 ([]) Yes ((([()]))) No ([()[] ()]) () Yes You may find it useful to use a text file for testing your code so that you do not have to keep retyping the tests. You can do this from the command line by typing the name of the executable file followed by a less than sign and the name of your file. For example, if my executable is named day7 then I could type: day7

Explanation / Answer

Ans.

public boolean valid(String a) {
   Stack<Character> stack = new Stack<Character>();
   for (char c : a.toCharArray()) {
       if (c == '(')
           stack.push(')');
       else if (c == '{')
           stack.push('}');
       else if (c == '[')
           stack.push(']');
       else if (stack.isEmpty() || stack.pop() != c)
           return false;
   }
   return stack.isEmpty();
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote