Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | Java program to implement the above approach ; Function to check if a string satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current character is equal to the previous character ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Reset value of cnt ; If count of consecutive 1 s is more than Q ; If count of consecutive 0 s is more than P ; Function to count all distinct binary strings that satisfy the given condition ; Stores the length of str ; If length of str is N ; If str satisfy the given condition ; If str does not satisfy the given condition ; Append a character '0' at end of str ; Append a character '1' at end of str ; Return total count of binary strings ; Driver Code
class GFG { static boolean checkStr ( String str , int P , int Q ) { int N = str . length ( ) ; char prev = str . charAt ( 0 ) ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str . charAt ( i ) == prev ) { cnt ++ ; } else { if ( prev == '1' && cnt >= Q ) { return false ; } if ( prev == '0' && cnt >= P ) { return false ; } cnt = 1 ; } prev = str . charAt ( i ) ; } if ( prev == '1' && cnt >= Q ) { return false ; } if ( prev == '0' && cnt >= P ) { return false ; } return true ; } static int cntBinStr ( String str , int N , int P , int Q ) { int len = str . length ( ) ; if ( len == N ) { if ( checkStr ( str , P , Q ) ) return 1 ; return 0 ; } int X = cntBinStr ( str + '0' , N , P , Q ) ; int Y = cntBinStr ( str + '1' , N , P , Q ) ; return X + Y ; } public static void main ( String [ ] args ) { int N = 5 , P = 2 , Q = 3 ; System . out . println ( cntBinStr ( " " , N , P , Q ) ) ; } }