Length of longest balanced parentheses prefix | Java Program to find length of longest balanced parentheses prefix . ; Return the length of longest balanced parentheses prefix . ; Traversing the string . ; If open bracket add 1 to sum . ; If closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; If sum is 0 , store the index value . ; Driven Program
import java . io . * ; class GFG { static int maxbalancedprefix ( String str , int n ) { int sum = 0 ; int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) sum += 1 ; else sum -= 1 ; if ( sum < 0 ) break ; if ( sum == 0 ) maxi = i + 1 ; } return maxi ; } public static void main ( String [ ] args ) { String str = " ( ( ( ) ( ) ) ( ) ) ( ( " ; int n = str . length ( ) ; System . out . println ( maxbalancedprefix ( str , n ) ) ; } }