Check if concatenation of two strings is balanced or not | Java 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 .
import java . util . Stack ; class GFG { static boolean isBalanced ( String s ) { Stack < Character > st = new Stack < Character > ( ) ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . charAt ( i ) == ' ( ' ) { st . push ( s . charAt ( i ) ) ; } else if ( st . empty ( ) ) { return false ; } else { st . pop ( ) ; } } if ( ! st . empty ( ) ) { return false ; } return true ; } static boolean isBalancedSeq ( String s1 , String s2 ) { if ( isBalanced ( s1 + s2 ) ) { return true ; } return isBalanced ( s2 + s1 ) ; } public static void main ( String [ ] args ) { String s1 = " ) ( ) ( ( ) ) ) ) " ; String s2 = " ( ( ) ( ( ) ( " ; if ( isBalancedSeq ( s1 , s2 ) ) { System . out . println ( " Balanced " ) ; } else { System . out . println ( " Not ▁ Balanced " ) ; } } }