Stack: Print Bracket Number

Problem Statement:

You are given expression, you need to print the bracket numbers

Example:

(a + (b*c))
1221

Solution:

Create a variable left_num = 1;
Create a stack right_num
Now traverse from 0 to n-1
if the exp[i] is ‘(‘, then print the left_num and push left_num into the stack and increment left_num by 1.
if the exp[i] is ‘)’, print the top element of the stack right_num and pop the element from the stack.
Time Complexity: O(n)
Space Complexity: O(n)

Code Solution

#include <iostream> 
#include <stack> 

using namespace std;

void solution(string exp, int n)
{

	int left_num = 1;
	
	stack<int> right_num;
	
	for (int i = 0; i < n; i++) 
	{
		
		if (exp[i] == '(') 
		{
			cout << left_num << " ";
			
			right_num.push(left_num);
			
			left_num++;
		}
		
		else if(exp[i] == ')') 
		{

			cout << right_num.top() << " ";
			
			right_num.pop();
		}
	}
}

int main()
{
	string exp = "(a+(b*c))+(d/e)";
	int n = exp.size();
	
	solution(exp, n);
	
	return 0;
}

Output

1 2 2 1 3 3
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *