Question

In: Computer Science

Write a pseudocode method to determine if a set of parentheses and brackets is balanced. For...

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 "[(])". 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

pseudocode method:

Boolean isBalance(S)

1. Set I=0

2. Repeat Step 3 While S[I] not equal to NULL do

3. IF S[I]= '(' then Push(S[I])

ELSE IF S[I]= '{' then Push(S[I])

ELSE IF S[I]= '[' then Push(S[I])

ELSE IF S[I]= ')' AND Peek() = '(' then Pop()

ELSE IF S[I]= '}' AND Peek() = '{' then Pop()

ELSE IF S[I]= ']' AND Peek() = '[' then Pop()

[End of IF]

[End of Loop]

4. IF Isempty() = True Return True

5. Else Return False

6. End

In this algorithm we are using a Stack data structure. At the beginning the stack is empty. Now read the given string from left to right until the end of the string. When a read symbol is open bracket (e.g. ( or { or [ ) then push it on to the stack. Otherwise, when a read symbol is close bracket (e.g. ) or } or ] ) and top of stack contains corresponding pair bracket then pop from the stack. Finally, check the stack is empty or not, if it is empty then brackets are balanced otherwise not balanced.

In this algorithm, extra memory for the stack data structure is needed, that is maximum of length of the given string. So, the space complexity is O(n) and time complexity also O(n).

Program in c++:

#include<iostream>
#include<stdlib.h>

using namespace std;

const int MAX = 100;

typedef struct stack
{
   char st[MAX];
   int top;
}stack;

stack stk;

void push(char x);
char pop();
char peek();

bool isbalance(char s[])
{
   for(int i=0; s[i]!='\0'; i++)
   {
       switch(s[i])
       {
           case '(':
           case '{':
           case '[':
               push(s[i]);
               break;
           case ')':
               if(peek()=='(') pop();
               break;
           case '}':
               if(peek()=='{') pop();
               break;
           case ']':
               if(peek()=='[') pop();
               break;
       }
   }
   if(stk.top==-1) return true;
  
   return false;
}

int main()
{
   int n,i,x;
   stk.top = -1;
   char s[MAX];

   cout<<"Enter string: :";
   cin>>s;
  
   bool f = isbalance(s);
  
   if(f==true)
       cout<<"Balanced"<<endl;
   else
       cout<<"Not Balanced"<<endl;
      
   return 0;
  
}

void push(char x)
{
if(stk.top==MAX-1){
   printf("Stack overflow\n");
return;
}
stk.st[++stk.top] = x;
}

char pop()
{
if(stk.top==-1){
   printf("Stack underflow\n");
return 0;
}
return stk.st[stk.top--];
}

char peek()
{
   return stk.st[stk.top];
}

Output:

Enter string: :[()]{}{[()()]()}
Balanced

Enter string: :[(])
Not Balanced


Related Solutions

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.
Algorithm design:Suppose that three types of parentheses are allowed in an expression: parentheses, square brackets, and...
Algorithm design:Suppose that three types of parentheses are allowed in an expression: parentheses, square brackets, and curly braces. Please design an efficient algorithm to determine whether the parentheses in the expression are correctly paired. Please write down the algorithm idea and steps. Please explain what kind of data structure is used to solve the problem, and then give the specific algorithm steps
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))", "{([]})", "{}())",...
Devise a Turing machine to check the correct nesting of brackets (parentheses). So, your machine should...
Devise a Turing machine to check the correct nesting of brackets (parentheses). So, your machine should start with a tape with something like (()()(())) on it and halt with T printed on the tape, and it should start with something like (()()(() on the tape and halt with F. That is, correctly nested strings of brackets should give T, and wrongly nested strings of brackets should give the answer F. This example is important since it shows that Turing machines...
write the pseudocode and code to solve the following: you are given a list. determine the...
write the pseudocode and code to solve the following: you are given a list. determine the sum of all the elements in the list without using the built in puthon function sum(). Take your code and create your own function and name it my_sum_algo() which will return the sum of numbers PS please write comments in the code for my understanding, and please write jn jn PYTHON 3 languge. Thank you, have a great day !
Write an algorithm in pseudocode for the binary search method using a while loop (iterative version)...
Write an algorithm in pseudocode for the binary search method using a while loop (iterative version) The recursive ternarySearch method returns true or false depending if the element was found or not. The ternarySearch method works in a similar manner to a binary search except it uses two mid values that “divide” the array into three portions. So, it needs to consider three recursive scenarios: See sample run: Accounts are: [0] 5658845 [1] 8080152 [2] 1005231 [3] 4520125 [4] 4562555...
Write an algorithm in pseudocode for the binary search method using a while loop (iterative version)...
Write an algorithm in pseudocode for the binary search method using a while loop (iterative version) The recursive ternarySearch method returns true or false depending if the element was found or not. The ternarySearch method works in a similar manner to a binary search except it uses two mid values that “divide” the array into three portions. So, it needs to consider three recursive scenarios: See sample run: Accounts are: [0] 5658845 [1] 8080152 [2] 1005231 [3] 4520125 [4] 4562555...
Exercise 1. Write an algorithm (pseudocode) to read a set of sales data items from standard...
Exercise 1. Write an algorithm (pseudocode) to read a set of sales data items from standard input and calculate and output their total and their average. Prompt user to enter number of data items. Exercise 2. Create a test data set to verify your algorithm. How many cases are needed? Explain. Write your test data set below for submission to the EOL dropbox upon completion of your lab. Number of items List data items Expected output Case 1: Exercise 3....
write pseudocode for the following problems not c code Pseudocode only Write a C program to...
write pseudocode for the following problems not c code Pseudocode only Write a C program to print all natural numbers from 1 to n. - using while loop Write a C program to print all natural numbers in reverse (from n to 1). - using while loop Write a C program to print all alphabets from a to z. - using while loop Write a C program to print all even numbers between 1 to 100. - using while loop...
Fibonacci Write pseudocode to calculate F(n) Write pseudocode to construct a vector of the first n...
Fibonacci Write pseudocode to calculate F(n) Write pseudocode to construct a vector of the first n numbers in the Fibonacci sequence. Write a function: fibo(n = 1){ # Your code here } which takes one parameter ​n​ and returns the ​nth​ fibonacci number. Use the function you wrote to calculate the 58th Fibonacci number. Include your R code in your report The Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) is defined as F(1) =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT