Question

In: Computer Science

Programming language is Java: Write a pseudocode method to determine if a set of parentheses and...

Programming language is Java:

Write a pseudocode method to determine if a set of parentheses and brackets is balanced. For example, such a method should return true for the string, "[()]{}{[()()]()}" and false for the string "[(])".

Also please discuss how the algorithm will perform and how much space in memory it will take if somebody passes a massive string as input.

Solutions

Expert Solution

static boolean check(String str){
       Stack<Character> ch=new Stack<Character>();
       int flag=0;
       // To check if a particular character is an opening bracket
       Set<Character> opening=new HashSet<>();
       opening.add('{');
       opening.add('(');
       opening.add('[');
       // To check if a particular character is a closing bracket and what is it's corresponding opening bracket
       HashMap<Character,Character> pair=new HashMap<>();
       pair.put('}','{');
       pair.put(')','(');
       pair.put(']','[');
       for(int i=0;i<str.length();i++){
           if(opening.contains(str.charAt(i))){
               ch.push(str.charAt(i));
           }
           else if(pair.containsKey(str.charAt(i))){
               if(!ch.isEmpty() && pair.get(str.charAt(i))==ch.peek()){
                   ch.pop();
               }
               else{
                   flag=1;
                   break;
               }      
           }
           else{
               // If any other characher is present, string is unbalanced
               flag=1;
               break;
           }          
       }
       if(ch.isEmpty() && flag==0)
           return true;
       else
           return false;
   }

The function takes O(n) time and O(n) space for an input string of length n.

O(n) time: Iterates over each Character of the string once

O(n) space: stores the characters in a stack. It will store all the characters of the string in worst case (all opening brackets or opening parentheses).


Related Solutions

Java programming language Write a Java application that simulates a test. The test contains at least...
Java programming language Write a Java application that simulates a test. The test contains at least five questions. Each question should be a multiple-choice question with 4 options. Design a QuestionBank class. Use programmer-defined methods to implement your solution. For example: - create a method to simulate the questions – simulateQuestion - create a method to check the answer – checkAnswer - create a method to display a random message for the user – generateMessage - create a method to...
In the programming language java: Write a class encapsulating the concept of a telephone number, assuming...
In the programming language java: Write a class encapsulating the concept of a telephone number, assuming a telephone number has only a single attribute: aString representing the telephone number. Include a constructor, the accessor and mutator, and methods 'toString' and 'equals'. Also include methods returning the AREA CODE (the first three digits/characters of the phone number; if there are fewer than three characters in the phone number of if the first three characters are not digits, then this method should...
Programming Language : JAVA Create an interface named Turner, with a single method called turn(). Then...
Programming Language : JAVA Create an interface named Turner, with a single method called turn(). Then create 4 classes: 1- Leaf: that implements turn(), which changes the color of the Leaf object and returns true. If for any reason it is unable to change color, it should return false (you can come up with a reason for failure). The new color can be determined at random. 2- Document: that implements turn(), which changes the page on the document to the...
Write a method called isMatch that takes a string of parentheses and check if all parentheses...
Write a method called isMatch that takes a string of parentheses and check if all parentheses match correctly. The parameter string might consist of other characters. Ignore other characters, just check the () {} [] public static boolean isMatch(String expressionLine); Use a JCF ArrayDeque or LinkedList as a stack to store all open or left parentheses. Use following main method to check your method. public static void main(String[] args) { String[] expression = new String[]{"{5*(x+2)+(y-1);}", "32*(20+(x[i]*3)-1", "((){([][])})", "({}((0))", "{([]})", "{}())",...
Javacc Parser Generation A) Select a non-java programming language B)Select a set of rules (for at...
Javacc Parser Generation A) Select a non-java programming language B)Select a set of rules (for at least three programming concepts e.g., conditionals, classes, loops etc.) from the language and write down the grammar rules (in BNF or EBNF) C) Create a .jj template file for this grammar (include 1) and 2) as comments in the file). Compile the .jj file and run the corresponding .java file D) As comments in the same jj file, show some expressions that were tested...
Write the following methods in a Java project: a) A Java method to determine and return...
Write the following methods in a Java project: a) A Java method to determine and return the sum of first three numbers, where three numbers are received as parameters. b) A Java method to determine and return the highest of N integers. The number of integers is received as a parameter. The method should prompt the user to enter the N numbers, then it return the highest. c) A Java method to determine and return an appropriate value indicating if...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
Java Programming Language Scenario: write a program that will prompt a user for 10 legendary people/characters....
Java Programming Language Scenario: write a program that will prompt a user for 10 legendary people/characters. After the entries are complete the program will display all 10 characters information. Store these characters in an array. Requirements: Create a user-defined class with the fields below: First Last Nickname Role Origin Create a main-source that will use the user-defined class and do the prompting. Create get/set methods in your user-defined class and methods in the main-source. Use an array to store the...
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement...
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement for a salesperson at a rate of $0.35 per mile. Your program should interact (ask the user to enter the data) with the user in this manner: MILEAGE REIMBURSEMENT CALCULATOR Enter beginning odometer reading > 13505.2 Enter ending odometer reading > 13810.6 You traveled 305.4 miles. At $0.35 per mile, your reimbursement is $106.89. ** Extra credit 6 points: Format the answer (2 points),...
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT