Check if a binary string has a 0 between 1 s or not | Set 1 ( General approach ) | Java program to check if a string is valid or not . ; Method returns 1 when string is valid else returns 0 ; Find first occurrence of 1 in s [ ] ; Find last occurrence of 1 in s [ ] ; Check if there is any 0 in range ; Driver method
class Test { static boolean checkString ( String s ) { int len = s . length ( ) ; int first = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( s . charAt ( i ) == '1' ) { first = i ; break ; } } int last = 0 ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( s . charAt ( i ) == '1' ) { last = i ; break ; } } for ( int i = first ; i <= last ; i ++ ) if ( s . charAt ( i ) == '0' ) return false ; return true ; } public static void main ( String args [ ] ) { String s = "00011111111100000" ; System . out . println ( checkString ( s ) ? " VALID " : " NOT ▁ VALID " ) ; } }