Given a string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, the task is to determine if brackets are balanced or not. Brackets are balanced if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Examples:
Input: str = “(())[]” Output: Yes Input: str = “))(({}{” Output: No
Approach:
- Keep two variables i and j to keep track of two brackets to be compared.
- Maintain a count whose value increments on encountering opening bracket and decrements on encountering a closing bracket.
- Set j = i, i = i + 1 and counter++ when opening brackets are encountered.
- When Closing brackets are encountered decrement count and compare brackets at i and j,
- If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ? 0.
- If brackets at i and j are not a match then return false.
- If count != 0 then return false.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool helperFunc( int & count, string& s, int & i, int & j, char tocom)
{
count--;
if (j > -1 && s[j] == tocom) {
s[i] = '#' ;
s[j] = '#' ;
while (j >= 0 && s[j] == '#' )
j--;
i++;
return 1;
}
else
return 0;
}
bool isValid(string s)
{
if (s.length() == 0)
return true ;
else {
int i = 0;
int count = 0;
int j = -1;
bool result;
while (i < s.length()) {
switch (s[i]) {
case '}' :
result = helperFunc(count, s, i, j, '{' );
if (result == 0) {
return false ;
}
break ;
case ')' :
result = helperFunc(count, s, i, j, '(' );
if (result == 0) {
return false ;
}
break ;
case ']' :
result = helperFunc(count, s, i, j, '[' );
if (result == 0) {
return false ;
}
break ;
default :
j = i;
i++;
count++;
}
}
if (count != 0)
return false ;
return true ;
}
}
int main()
{
string str = "[[]][]()" ;
if (isValid(str))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static String s = "[[]][]()" ;
static int count = 0 ;
static int i = 0 ;
static int j = - 1 ;
static int helperFunc( char tocom)
{
count--;
char temp = s.charAt(j);
if (j > - 1 && temp == tocom)
{
s = s.replace(s.charAt(i), '#' );
s = s.replace(s.charAt(j), '#' );
temp = s.charAt(j);
while (j >= 0 && temp == '#' )
j--;
i++;
return 1 ;
}
else
return 0 ;
}
static boolean isValid()
{
if (s.length() == 0 )
return true ;
else {
int result;
while (i < s.length())
{
char temp = s.charAt(i);
if (temp== '}' )
{
result = helperFunc( '{' );
if (result == 0 )
{
return false ;
}
}
else if (temp == ')' )
{
result = helperFunc( '(' );
if (result == 0 )
{
return false ;
}
}
else if (temp == ']' )
{
result = helperFunc( '[' );
if (result == 0 )
{
return false ;
}
}
else
{
j = i;
i++;
count++;
}
}
if (count != 0 )
return false ;
return true ;
}
}
public static void main(String args[])
{
if (isValid())
System.out.println( "No" );
else
System.out.println( "Yes" );
}
}
|
Python3
count = 0
i = 0
j = - 1
def helperFunc(s, tocom):
global i, j, count
count - = 1
if j > - 1 and s[j] = = tocom:
s[i] = '#'
s[j] = '#'
while j > = 0 and s[j] = = '#' :
j - = 1
i + = 1
return 1
else :
return 0
def isValid(s):
global i, j, count
if len (s) = = 0 :
return True
else :
result = False
while i < len (s):
if s[i] = = '}' :
result = helperFunc(s, '{' )
if result = = 0 :
return False
elif s[i] = = ')' :
result = helperFunc(s, '(' )
if result = = 0 :
return False
elif s[i] = = ']' :
result = helperFunc(s, '[' )
if result = = 0 :
return False
else :
j = i
i + = 1
count + = 1
if count ! = 0 :
return False
return True
if __name__ = = "__main__" :
string = "[[]][]()"
string = list (string)
print ( "Yes" ) if isValid(string) else print ( "No" )
|
C#
using System;
class GFG{
static string s = "[[]][]()" ;
static int count = 0;
static int i = 0;
static int j = -1;
static int helperFunc( char tocom)
{
count--;
char temp = s[j];
if (j > -1 && temp == tocom)
{
s = s.Replace(s[i], '#' );
s = s.Replace(s[j], '#' );
temp = s[j];
while (j >= 0 && temp == '#' )
j--;
i++;
return 1;
}
else
return 0;
}
static bool isValid()
{
if (s.Length == 0)
return true ;
else
{
int result;
while (i < s.Length)
{
char temp = s[i];
if (temp == '}' )
{
result = helperFunc( '{' );
if (result == 0)
{
return false ;
}
}
else if (temp == ')' )
{
result = helperFunc( '(' );
if (result == 0)
{
return false ;
}
}
else if (temp == ']' )
{
result = helperFunc( '[' );
if (result == 0)
{
return false ;
}
}
else
{
j = i;
i++;
count++;
}
}
if (count != 0)
return false ;
return true ;
}
}
public static void Main( string []args)
{
if (isValid())
{
Console.Write( "No" );
}
else
{
Console.Write( "Yes" );
}
}
}
|
Javascript
var i = 0;
var count = 0;
var j = -1;
var s;
function helperFunc(tocom)
{
count--;
if (j > -1 && s[j] == tocom) {
s[i] = '#' ;
s[j] = '#' ;
while (j >= 0 && s[j] == '#' )
j--;
i++;
return 1;
}
else
return 0;
}
function isValid(str)
{
s = str.split( "" )
if (s.length == 0)
return true ;
else {
let result;
while (i < s.length) {
switch (s[i]) {
case '}' :
result = helperFunc( '{' );
if (result == 0) {
return false ;
}
break ;
case ')' :
result = helperFunc( '(' );
if (result == 0) {
return false ;
}
break ;
case ']' :
result = helperFunc( '[' );
if (result == 0) {
return false ;
}
break ;
default :
j = i;
i++;
count++;
}
}
if (count != 0)
return false ;
return true ;
}
}
let str = "[[]][]()" ;
if (isValid(str))
console.log( "Yes" );
else
console.log( "No" );
|
Time complexity: O(N^2) where N is length of input expression string
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!