Question:
How to check whether string (of brackets) is balanced or not using C++

Summary

Let’s consider:

The function should return ‘true’ for exp= [()]{}{[()()]()} and ‘false’ for exp= [(]). 


Let’s assume we use:

Method- ispar


Solution


class Solution

{

    public:

    //Function to check if brackets are balanced or not.

    bool ispar(string x)

    {

        // Your code here

        stack<char> st;

        for(int i=0; i<x.size(); i++){

            if(st.empty()) st.push(x[i]);

            else if(st.top()=='(' && x[i]==')' || st.top()=='{' && x[i]=='}' || st.top()=='[' && x[i]==']'){

                st.pop();

            }

            else{

                st.push(x[i]);

            }

        }

        if(st.empty()) return true;

        else return false;

    }


};


Explanation:


Stack Initialization:

  • A stack of characters (st) is initialized to keep track of opening brackets.


Iteration through the String:

  • The code iterates through each character in the input string.


Stack Operations:

  • If the stack is empty, the current character is pushed onto the stack.


Answered by:> >ss6699

Credit:> >GeekforGeeks


Suggested blogs:

>How to configure python in jmeter?

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers