Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++

C++Server Side ProgrammingProgramming

Concept

With respect of given a string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, the task is to find if brackets are balanced or not.

Brackets are denoted as balanced if −

  • We close open brackets must be closed by the same type of brackets.

  • Again we close open brackets according to the correct order.

Input − str = “(()){}”

Output − Yes

Input − str = “))(([][”

Output − No

Method

  • Assign two variables a and b to keep track of two brackets to be compared.

  • A count should be maintained whose value increments on encountering opening bracket and decrements on encountering a closing bracket.

  • Assign b = a, a = a + 1 and count=count+1 when opening brackets are encountered.

  • At the time when closing brackets are encountered decrement count and compare brackets at i and j,

    • If it has been seen that brackets at a and b are a match, then substitute ‘#’ in string at a th and b th position. a is incremented and b is decremented until non ‘#’ value is encountered or b ≥ 0.

    • If it has been seen that brackets at a and b are not a match then return false.

  • If count != 0 then return false.

Example

 Live Demo

// C++ implementation of the approach
#include <iostream>
using namespace std;
bool helperFunc(int& count1, string& s1, int& i1, int& j1, char tocom1){
   count1--;
   if (j1 > -1 && s1[j1] == tocom1) {
      s1[i1] = '#';
      s1[j1] = '#';
      while (j1 >= 0 && s1[j1] == '#')
         j1--;
      i1++;
      return 1;
   }
   else
      return 0;
}
bool isValid(string s1){
   if (s1.length() == 0)
      return true;
   else {
      int i1 = 0;
      int count1 = 0;
      int j1 = -1;
      bool result1;
      while (i1 < s1.length()) {
         switch (s1[i1]) {
            case '}':
               result1 = helperFunc(count1, s1, i1, j1, '{');
               if (result1 == 0) {
                  return false;
               }
            break;
            case ')':
               result1 = helperFunc(count1, s1, i1, j1, '(');
               if (result1 == 0) {
                  return false;
               }
            break;
            case ']':
               result1 = helperFunc(count1, s1, i1, j1, '[');
               if (result1 == 0) {
                  return false;
               }
            break;
            default:
               j1 = i1;
               i1++;
               count1++;
            }
         }
         if (count1 != 0)
            return false;
         return true;
   }
}
// Driver code
int main(){
   string str1 = "[[]][]()";
   if (isValid(str1))
      cout << "Yes";
   else
      cout << "No";
   return 0;
}

Output

Yes
raja
Published on 23-Jul-2020 07:36:42
Advertisements