Check if a binary string has two consecutive occurrences of one everywhere | Java implementation of the approach ; Function that returns 1 if str is valid ; Index of first appearance of ' b ' ; If str starts with ' b ' ; While ' b ' occurs in str ; If ' b ' doesn ' t ▁ appear ▁ after ▁ an ▁ ' a ' ; If ' b ' is not succeeded by another ' b ' ; If sub - string is of the type " abbb " ; If str ends with a single b ; Driver code
class GFG { private static boolean isValidString ( String str , int n ) { int index = str . indexOf ( " b " ) ; if ( index == 0 ) return false ; while ( index != - 1 ) { if ( str . charAt ( index - 1 ) != ' a ' ) return false ; if ( index + 1 < n && str . charAt ( index + 1 ) != ' b ' ) return false ; if ( index + 2 < n && str . charAt ( index + 2 ) == ' b ' ) return false ; if ( index == n - 1 ) return false ; index = str . indexOf ( " b " , index + 2 ) ; } return true ; } public static void main ( String [ ] args ) { String str = " abbaaabbabba " ; int n = str . length ( ) ; System . out . println ( isValidString ( str , n ) ) ; } }