Check if a binary string has a 0 between 1s or not | Set 1 (General approach) - GeeksforGeeks

20 May, 2021
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1’s. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. One approach to solving the problem is discussed here, other using Regular expressions is given Set 2 Examples: 
Input : 100
Output : VALID

Input : 1110001
Output : NOT VALID
There is 0 between 1s

Input : 00011
Output : VALID
Suppose we have a string: 01111011110000Now take two variables say A and B. run a loop for 0 to length of the string and point Ato the first occurrence of 1, after that again run a loop from length of the string to 0and point second variable to the last occurrence of 1.So A = 1 (Position of first ‘1’ is the string) and B = 9 (last occurrence of ‘1’).Now run a loop from A to B and check that ‘0’ is present between 1 or not, if “YES” thanset flag to 1 and break the loop, else set flag to 0.In this case flag will set to 1 as the given string is not valid and print “NOT VALID”.
C++
Java
Python
C#
Javascript
// C++ program to check if a string is valid or not.#include <bits/stdc++.h>using namespace std; // Function returns 1 when string is valid// else returns 0bool checkString(string s){    int len = s.length();     // Find first occurrence of 1 in s[]    int first = s.size() + 1;    for (int i = 0; i < len; i++) {        if (s[i] == '1') {            first = i;            break;        }    }     // Find last occurrence of 1 in s[]    int last = 0;    for (int i = len - 1; i >= 0; i--) {        if (s[i] == '1') {            last = i;            break;        }    }     // Check if there is any 0 in range    for (int i = first; i <= last; i++)        if (s[i] == '0')            return false;     return true;} // Driver codeint main(){    string s = "00011111111100000";    checkString(s) ? cout << "VALID\n" : cout << "NOT VALID\n";    return 0;}
// Java program to check if a string is valid or not. class Test {    // Method returns 1 when string is valid    // else returns 0    static boolean checkString(String s)    {        int len = s.length();         // Find first occurrence of 1 in s[]        int first = 0;        for (int i = 0; i < len; i++) {            if (s.charAt(i) == '1') {                first = i;                break;            }        }         // Find last occurrence of 1 in s[]        int last = 0;        for (int i = len - 1; i >= 0; i--) {            if (s.charAt(i) == '1') {                last = i;                break;            }        }         // Check if there is any 0 in range        for (int i = first; i <= last; i++)            if (s.charAt(i) == '0')                return false;         return true;    }     // Driver method    public static void main(String args[])    {        String s = "00011111111100000";        System.out.println(checkString(s) ? "VALID" : "NOT VALID");    }}
# Python3 program to check if# a string is valid or not. # Function returns 1 when# string is valid else# returns 0def checkString(s):       Len = len(s)         # Find first occurrence    # of 1 in s[]    first = len(s) + 1     for i in range(Len):        if(s[i] == '1'):            first = i            break     # Find last occurrence    # of 1 in s[]    last = 0     for i in range(Len - 1,                   -1, -1):        if(s[i] == '1'):            last = i            break     # Check if there is any    # 0 in range    for i in range(first,                   last + 1):        if(s[i] == '0'):            return False    return True # Driver codes = "00011111111100000"if(checkString(s)):    print("VALID")else:    print("NOT VALID") # This code is contributed by avanitrachhadiya2155
// C# program to check if a// string is valid or not.using System; class GFG {         // Method returns 1 when string is valid    // else returns 0    static bool checkString(String s)    {        int len = s.Length;         // Find first occurrence of 1 in s[]        int first = 0;        for (int i = 0; i < len; i++) {            if (s[i] == '1') {                first = i;                break;            }        }         // Find last occurrence of 1 in s[]        int last = 0;        for (int i = len - 1; i >= 0; i--) {            if (s[i] == '1') {                last = i;                break;            }        }         // Check if there is any 0 in range        for (int i = first; i <= last; i++)            if (s[i] == '0')                return false;         return true;    }     // Driver method    public static void Main()    {        string s = "00011111111100000";        Console.WriteLine(checkString(s) ?                   "VALID" : "NOT VALID");    }} // This code is contributed by Sam007
<script>     // JavaScript program to check     // if a string is valid or not.         // Method returns 1 when string is valid    // else returns 0    function checkString(s)    {        let len = s.length;           // Find first occurrence of 1 in s[]        let first = 0;        for (let i = 0; i < len; i++) {            if (s[i] == '1') {                first = i;                break;            }        }           // Find last occurrence of 1 in s[]        let last = 0;        for (let i = len - 1; i >= 0; i--) {            if (s[i] == '1') {                last = i;                break;            }        }           // Check if there is any 0 in range        for (let i = first; i <= last; i++)            if (s[i] == '0')                return false;           return true;    }         let s = "00011111111100000";    document.write(checkString(s) ?                      "VALID" : "NOT VALID");     </script>
Output:  
VALID
Time Complexity: O(n)
YouTubeGeeksforGeeks501K subscribersCheck if a binary string has a 0 between 1s or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:43•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IDLxFCKdJaY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
avanitrachhadiya2155
divyeshrabadiya07
binary-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 String Coding Problems for Interviews
Hill Cipher
Naive algorithm for Pattern Searching
Vigenère Cipher
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Converting Roman Numerals to Decimal lying between 1 to 3999
Print all subsequences of a string
Program to count occurrence of a given character in a string