Thursday, March 17, 2022

Parenthesis Checker - Balance Parenthesis GFG problem

 Parenthesis Checker 

Easy

Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”.

Example 1:

Input:
{([])}
Output: 
true
Explanation: 
{ ( [ ] ) }. Same colored brackets can form 
balaced pairs, with 0 number of 
unbalanced bracket.

Example 2:

Input: 
()
Output: 
true
Explanation: 
(). Same bracket can form balanced pairs, 
and here only 1 type of bracket is 
present and in balanced way.

Example 3:

Input: 
([]
Output: 
false
Explanation: 
([]. Here square bracket is balanced but 
the small bracket is not balanced and 
Hence , the output will be unbalanced.

Your Task:
This is a function problem. You only need to complete the function ispar() that takes a string as a parameter and returns a boolean value true if brackets are balanced else returns false. The printing is done automatically by the driver code.


Expected Time Complexity: O(|x|)
Expected Auixilliary Space: O(|x|)


Constraints:
1 ≤ |x| ≤ 
32000

Note: The drive code prints "balanced" if function return true, otherwise it prints "not balanced".

Practice Here:

Parenthesis Checker | Practice | GeeksforGeeks


Solution:


class Solution

{

    public:

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

    bool ispar(string x)

    {

        // Your code here

        stack<char> st;

        for(char c: x)

        {

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

            st.push(c);

            else {

                if(st.empty())

                return false;

                if((c==')'&&st.top()=='(')||(c=='}'&&st.top()=='{')||(c==']'&&st.top()=='['))

                st.pop();

                else return false;

            }

        }

       return st.empty();

    }

};




No comments:

Implement stsStr Leetcode solution

  28.   Implement strStr() Easy Implement  strStr() . Given two strings  needle  and  haystack , return the index of the first occurrence of...