Length of the longest substring with equal 1 s and 0 s | Java program to find the length of the longest balanced substring ; Function to check if a string contains equal number of one and zeros or not ; Function to find the length of the longest balanced substring ; Driver code ; Function call
import java . io . * ; import java . util . * ; class GFG { public static boolean isValid ( String p ) { int n = p . length ( ) ; int c1 = 0 , c0 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( p . charAt ( i ) == '0' ) { c0 ++ ; } if ( p . charAt ( i ) == '1' ) { c1 ++ ; } } if ( c0 == c1 ) { return true ; } else { return false ; } } public static int longestSub ( String s ) { int max_len = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( isValid ( s . substring ( i , j + 1 ) ) && max_len < j - i + 1 ) { max_len = j - i + 1 ; } } } return max_len ; } public static void main ( String [ ] args ) { String s = "101001000" ; System . out . println ( longestSub ( s ) ) ; } }