Open In App

Check if given Binary string follows then given condition or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given binary string str, the task is to check whether the given string follows the below condition or not: 
 

  • String starts with a ‘1’.
  • Each ‘1’ is followed by empty string(“”), ‘1’, or “00”.
  • Each “00” is followed by empty string(“”), ‘1’.

If the given string follows the above criteria then print “Valid String” else print “Invalid String”.
Examples: 
 

Input: str = “1000” 
Output: False 
Explanation: 
The given string starts with “1” and has “00” followed by the “1” which is not the given criteria. 
Hence, the given string is “Invalid String”.
Input: str = “1111” 
Output: True 
Explanation: 
The given string starts with 1 and has 1 followed by all the 1’s. 
Hence, the given string is “Valid String”. 
 

Approach:

  1. Check if the first character of the string is ‘1’, if not, return false.
  2. Traverse the string character by character, starting from the second character.
  3. If the current character is ‘1’, move to the next character.
  4. If the current characters are “00”, move two characters ahead and check if the next character is ‘1’, if not, return false.
  5. If the current character is neither ‘1’ nor “00”, return false.
  6. If we reach the end of the string without returning false, the string is valid. Return true.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the
// string follows rules or not
bool checkrules(string s)
{
    int n = s.length();
    int i = 0;
 
    // Check if the string starts with '1'
    if (s[i] != '1') {
        return false;
    }
    i++;
 
    // Traverse the string character by character
    while (i < n) {
        // Check if the current character is '1'
        if (s[i] == '1') {
            i++;
        }
        // Check if the current characters are "00"
        else if (i + 1 < n && s[i] == '0'
                 && s[i + 1] == '0') {
            i += 2;
            // Check if the next character is '1'
            if (i < n && s[i] != '1') {
                return false;
            }
        }
        // If the current character is neither '1' nor "00",
        // the string is invalid
        else {
            return false;
        }
    }
 
    // If we reach the end of the string, it is valid
    return true;
}
 
// Driver Code
int main()
{
    // Given String str
    string str = "1111";
 
    // Function Call
    if (checkrules(str)) {
        cout << "Valid String";
    }
    else {
        cout << "Invalid String";
    }
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
public class Main {
 
    // Function to check if the
    // string follows rules or not
    public static boolean checkrules(String s)
    {
        int n = s.length();
        int i = 0;
 
        // Check if the string starts with '1'
        if (s.charAt(i) != '1') {
            return false;
        }
        i++;
 
        // Traverse the string character by character
        while (i < n) {
            // Check if the current character is '1'
            if (s.charAt(i) == '1') {
                i++;
            }
            // Check if the current characters are "00"
            else if (i + 1 < n && s.charAt(i) == '0'
                     && s.charAt(i + 1) == '0') {
                i += 2;
                // Check if the next character is '1'
                if (i < n && s.charAt(i) != '1') {
                    return false;
                }
            }
            // If the current character is neither '1' nor
            // "00", the string is invalid
            else {
                return false;
            }
        }
 
        // If we reach the end of the string, it is valid
        return true;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given String str
        String str = "1111";
 
        // Function Call
        if (checkrules(str)) {
            System.out.println("Valid String");
        }
        else {
            System.out.println("Invalid String");
        }
    }
}
// This code is contributed by Prajwal Kandekar


Python3




# Function to check if the
# string follows rules or not
 
 
def check_rules(s):
    n = len(s)
    i = 0
 
    # Check if the string starts with '1'
    if s[i] != '1':
        return False
    i += 1
 
    # Traverse the string character by character
    while i < n:
        # Check if the current character is '1'
        if s[i] == '1':
            i += 1
        # Check if the current characters are "00"
        elif i + 1 < n and s[i] == '0' and s[i + 1] == '0':
            i += 2
            # Check if the next character is '1'
            if i < n and s[i] != '1':
                return False
        # If the current character is neither '1' nor
        # "00", the string is invalid
        else:
            return False
 
    # If we reach the end of the string, it is valid
    return True
 
 
# Driver Code
# Given String str
str = "1111"
 
# Function Call
if check_rules(str):
    print("Valid String")
else:
    print("Invalid String")


C#




using System;
 
public class Program
{
  // Function to check if the
  // string follows rules or not
  public static bool CheckRules(string s)
  {
    int n = s.Length;
    int i = 0;
 
    // Check if the string starts with '1'
    if (s[i] != '1')
    {
      return false;
    }
    i++;
 
    // Traverse the string character by character
    while (i < n)
    {
      // Check if the current character is '1'
      if (s[i] == '1')
      {
        i++;
      }
      // Check if the current characters are "00"
      else if (i + 1 < n && s[i] == '0'
               && s[i + 1] == '0')
      {
        i += 2;
        // Check if the next character is '1'
        if (i < n && s[i] != '1')
        {
          return false;
        }
      }
      // If the current character is neither '1' nor "00",
      // the string is invalid
      else
      {
        return false;
      }
    }
 
    // If we reach the end of the string, it is valid
    return true;
  }
 
  // Driver Code
  public static void Main()
  {
    // Given String str
    string str = "1111";
 
    // Function Call
    if (CheckRules(str))
    {
      Console.WriteLine("Valid String");
    }
    else
    {
      Console.WriteLine("Invalid String");
    }
  }
}


Javascript




// JavaScript program for the above approach
 
// Function to check if the
// string follows rules or not
function checkrules(s) {
    let n = s.length;
    let i = 0;
 
    // Check if the string starts with '1'
    if (s[i] !== '1') {
        return false;
    }
    i++;
 
    // Traverse the string character by character
    while (i < n) {
        // Check if the current character is '1'
        if (s[i] === '1') {
            i++;
        }
        // Check if the current characters are "00"
        else if (i + 1 < n && s[i] === '0' && s[i + 1] === '0') {
            i += 2;
            // Check if the next character is '1'
            if (i < n && s[i] !== '1') {
                return false;
            }
        }
        // If the current character is neither '1' nor "00", the string is invalid
        else {
            return false;
        }
    }
 
    // If we reach the end of the string, it is valid
    return true;
}
 
// Driver Code
let str = "1111";
 
// Function Call
if (checkrules(str)) {
    console.log("Valid String");
} else {
    console.log("Invalid String");
}


Output

Valid String

Time Complexity: O(N)

Auxiliary Space: O(1)

Approach: The idea is to use Recursion. Below are the steps: 
 

  1. Check whether 0th character is ‘1’ or not. If it is not ‘1’, return false as the string is not following condition 1.
  2. To check the string satisfying the second condition, recursively call for a string starting from 1st index using substr() function in C++.
  3. To check the string satisfying the third condition, first, we need to check if the string length is greater than 2 or not. If yes, then check if ‘0’ is present at the first and second index. If yes, then recursively call for the string starting from 3rd index.
  4. At any recursive call, If the string is empty, then we have traversed the complete string satisfying all the given conditions and print “Valid String”.
  5. At any recursive call, If the given condition doesn’t satisfy then stop that recursion and print “Invalid String”.

Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if the
// string follows rules or not
bool checkrules(string s)
{
    if (s.length() == 0)
        return true;
 
    // Check for the first condition
    if (s[0] != '1')
        return false;
 
    // Check for the third condition
    if (s.length() > 2) {
        if (s[1] == '0' && s[2] == '0')
            return checkrules(s.substr(3));
    }
 
    // Check for the second condition
    return checkrules(s.substr(1));
}
 
// Driver Code
int main()
{
    // Given String str
    string str = "1111";
 
    // Function Call
    if (checkrules(str)) {
        cout << "Valid String";
    }
    else {
        cout << "Invalid String";
    }
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if the
// String follows rules or not
static boolean checkrules(String s)
{
    if (s.length() == 0)
        return true;
 
    // Check for the first condition
    if (s.charAt(0) != '1')
        return false;
 
    // Check for the third condition
    if (s.length() > 2)
    {
        if (s.charAt(1) == '0' &&
            s.charAt(2) == '0')
            return checkrules(s.substring(3));
    }
 
    // Check for the second condition
    return checkrules(s.substring(1));
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String str
    String str = "1111";
 
    // Function call
    if (checkrules(str))
    {
        System.out.print("Valid String");
    }
    else
    {
        System.out.print("Invalid String");
    }
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 program for the above approach
 
# Function to check if the
# string follows rules or not
def checkrules(s):
     
    if len(s) == 0:
        return True
         
    # Check for the first condition
    if s[0] != '1':
        return False
         
    # Check for the third condition
    if len(s) > 2:
        if s[1] == '0' and s[2] == '0':
            return checkrules(s[3:])
             
    # Check for the second condition
    return checkrules(s[1:])
     
# Driver code
if __name__ == '__main__':
     
    # Given string
    s = '1111'
     
    # Function call
    if checkrules(s):
        print('valid string')
    else:
        print('invalid string')
         
# This code is contributed by virusbuddah_


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if the
// String follows rules or not
static bool checkrules(String s)
{
    if (s.Length == 0)
        return true;
 
    // Check for the first condition
    if (s[0] != '1')
        return false;
 
    // Check for the third condition
    if (s.Length > 2)
    {
        if (s[1] == '0' &&
            s[2] == '0')
            return checkrules(s.Substring(3));
    }
 
    // Check for the second condition
    return checkrules(s.Substring(1));
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String str
    String str = "1111";
 
    // Function call
    if (checkrules(str))
    {
        Console.Write("Valid String");
    }
    else
    {
        Console.Write("Invalid String");
    }
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to check if the
// string follows rules or not
function checkrules(s)
{
    if (s.length == 0)
        return true;
 
    // Check for the first condition
    if (s[0] != '1')
        return false;
 
    // Check for the third condition
    if (s.length > 2) {
        if (s[1] == '0' && s[2] == '0')
            return checkrules(s.substring(3));
    }
 
    // Check for the second condition
    return checkrules(s.substring(1));
}
 
// Driver Code
// Given String str
var str = "1111";
// Function Call
if (checkrules(str)) {
    document.write( "Valid String");
}
else {
    document.write( "Invalid String");
}
 
</script>


Output

Valid String

Time Complexity: O(N), where N is the length of string. 
Auxiliary Space: O(1).



Last Updated : 11 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads