Question

In: Computer Science

Using a Stack, describe the algorithm below (with pre conditions and post conditions) how you would...

  1. Using a Stack, describe the algorithm below (with pre conditions and post conditions) how you would check a block of code and be sure it has the appropriate amount of curly brackets { }. (java)

Solutions

Expert Solution

Given an piece of code, how to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct.

Example:

Input: exp = “[()]{}{[()()]()}”
Output: correct

Input: exp = “[(])”
Output: Not correct

Algorithm:

  • Declare a character stack S.
  • Now traverse the expression string exp.
    1. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
    2. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
  • After complete traversal, if there is some starting bracket left in stack then “not balanced”

// Java program for checking

// balanced Parenthesis

import java.util.*;

public class BalancedParan

{

    // function to check if paranthesis are balanced

    static boolean areParanthesisBalanced(String expr)

    {

        // Using ArrayDeque is faster than using Stack class

        Deque<Character> stack

            = new ArrayDeque<Character>();

        // Traversing the Expression

        for (int i = 0; i < expr.length(); i++)

        {

            char x = expr.charAt(i);

            if (x == '(' || x == '[' || x == '{')

            {

                // Push the element in the stack

                stack.push(x);

                continue;

            }

            // IF current current character is not opening

            // bracket, then it must be closing. So stack

            // cannot be empty at this point.

            if (stack.isEmpty())

                return false;

            char check;

            switch (x)

            {

            case ')':

                check = stack.pop();

                if (check == '{' || check == '[')

                    return false;

                break;

            case '}':

                check = stack.pop();

                if (check == '(' || check == '[')

                    return false;

                break;

            case ']':

                check = stack.pop();

                if (check == '(' || check == '{')

                    return false;

                break;

            }

        }

        // Check Empty Stack

        return (stack.isEmpty());

    }

    // Driver code

    public static void main(String[] args)

    {

        String expr = "([{}])";

       

        // Function call

        if (areParanthesisBalanced(expr))

            System.out.println("Balanced ");

        else

            System.out.println("Not Balanced ");

    }

}

Output

Balanced

Time Complexity: O(n)
Auxiliary Space: O(n) for stack


Related Solutions

What do you understand by pre- and post-conditions of a function? Write the pre- and post-conditions...
What do you understand by pre- and post-conditions of a function? Write the pre- and post-conditions to axiomatically specify the following functions: (a) A function takes two floating point numbers representing the sides of a rectangle as input and returns the area of the corresponding rectangle as output. (b) A function accepts three integers in the range of -100 and +100 and determines the largest of the three integers. (c) A function takes an array of integers as input and...
Stack ADT What would you say is the most important drawback of using the stack that...
Stack ADT What would you say is the most important drawback of using the stack that should be considered before choosing it for use in a real application? Typed out please.
solution using stack Reversing a word or a sentence: Write an algorithm that will display a...
solution using stack Reversing a word or a sentence: Write an algorithm that will display a given word in a reverse order. - e.g. "Data Structures" will be "serutcurtS ataD".
post and pre exercise and how it affects the lungs
post and pre exercise and how it affects the lungs
Implement in Python using stack operations. Postfix Calculator Post fix calculator • We use a stack...
Implement in Python using stack operations. Postfix Calculator Post fix calculator • We use a stack • When an operand is read, push it on statck • When an operator is read i.e +, *. /, - – Pop two from the top of the stack and apply the operator and push the result on stack if there is one value instead of two display an error message • Keep repeating until an equal sign, = is read; pop from...
How would you respond to the post below? The ethical values of an establishment can influence...
How would you respond to the post below? The ethical values of an establishment can influence its performance of a business. It is a factor that will impact their relationship with consumers and productivity within the workplace. They must display ethical consciousness to become a successful business in the global market. Ethics refers to the values of an individual that differentiate right from wrong ( Warrick, 2016). Ethical companies have a high chance of meeting the needs of consumers because...
Provide code and assertion statements for the pre/post-conditions. (To execute the assertion code, the java.exe requires...
Provide code and assertion statements for the pre/post-conditions. (To execute the assertion code, the java.exe requires the option -ea for the VM). // *** MyArrayList is limited to 100 elements. *** public class MyArrayList<E> extends ArrayList<E> { public MyArrayList() { // assert postcondition } @Override public int size() { // assert postcondition // code } // Insert e as a new first element to mal public void insertFirst(E e) { // assert precondition // code // assert postcondition } //...
Post an initial response to the discussion prompt and describe and explain how you would use...
Post an initial response to the discussion prompt and describe and explain how you would use at least two rules to verify and validate each pair of the analysis model against each other as follows: Two rules to verify and validate the functional and structural models Two rules to verify and validate the functional and behavioral models Two rules to verify and validate the structural and behavioral models Reply to two of your peers’ posts and comment on the responses...
Describe how information is passed from the pre-synaptic to post-synaptic neuron in order to allow information...
Describe how information is passed from the pre-synaptic to post-synaptic neuron in order to allow information flow throughout the nervous system.
1) Write a post on the three procedures below. Discuss how you would change the quality...
1) Write a post on the three procedures below. Discuss how you would change the quality but not the quantity of a proposition. Discuss how you would Change the quantity but not the quality of a proposition. Discuss how you would change the quality and the quantity of a proposition.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT