Check if concatenation of two strings is balanced or not | CPP program to check if sequence obtained by concatenating two bracket sequences is balanced or not . ; Check if given string is balanced bracket sequence or not . ; If current bracket is an opening bracket push it to stack . ; If current bracket is a closing bracket then pop from stack if it is not empty . If stack is empty then sequence is not balanced . ; If stack is not empty , then sequence is not balanced . ; Function to check if string obtained by concatenating two bracket sequences is balanced or not . ; Check if s1 + s2 is balanced or not . ; Check if s2 + s1 is balanced or not . ; Driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBalanced ( string s ) { stack < char > st ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ( ' ) st . push ( s [ i ] ) ; else { if ( st . empty ( ) ) { return false ; } else st . pop ( ) ; } } if ( ! st . empty ( ) ) return false ; return true ; } bool isBalancedSeq ( string s1 , string s2 ) { if ( isBalanced ( s1 + s2 ) ) return true ; return isBalanced ( s2 + s1 ) ; } int main ( ) { string s1 = " ) ( ) ( ( ) ) ) ) " ; string s2 = " ( ( ) ( ( ) ( " ; if ( isBalancedSeq ( s1 , s2 ) ) cout << " Balanced " ; else cout << " Not ▁ Balanced " ; return 0 ; }