Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
Last Updated :
17 Jan, 2023
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. Examples:
Input : 100
Output : VALID
Input : 1110001
Output : NOT VALID
There is 0 between 1s
Input : 00011
Output : VALID
In Set 1, we have discussed general approach for validity of string.In this post, we will discuss regular expression approach for same and it is simple. As we know that in a string if there is zero between 1’s, than string is not valid.Hence below is one of the regular expression for invalid string pattern.
10+1
So here is the simple regex algorithm.
- Loop over the matcher(string)
- if above regex match is find in the matcher, then string is not valid, otherwise valid.
Implementation:
C++
#include <iostream>
#include <regex>
using namespace std;
bool checkString(string str)
{
const regex Regex( "10+1" );
return !regex_match(str, Regex);
}
int main()
{
string str = "00011111111100000" ;
cout<<(checkString(str) ? "VALID"
: "NOT VALID" );
return 0;
}
|
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG
{
static boolean checkString(String str)
{
String regex = "10+1" ;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find())
{
return false ;
}
return true ;
}
public static void main (String[] args)
{
String str = "00011111111100000" ;
System.out.println(checkString(str) ? "VALID" : "NOT VALID" );
}
}
|
Python3
import re
def checkString( str ):
regex = "10+1"
x = re.search( "10+1" , str )
return x is None
str = "00011111111100000"
if checkString( str ):
print ( "VALID" )
else :
print ( "NOT VALID" )
|
C#
using System;
using System.Text.RegularExpressions;
class GFG {
static bool checkString( string str)
{
Regex regex = new Regex( @"10+1" );
return !regex.IsMatch(str);
}
public static void Main( string [] args)
{
string str = "00011111111100000" ;
Console.WriteLine(checkString(str) ? "VALID"
: "NOT VALID" );
}
}
|
Javascript
function checkString(str)
{
return str.match(/^[0-1]+$/) != null ;
}
let str = "01" ;
console.log(checkString(str) ? "VALID" : "NOT VALID" );
|
Time complexity : O(n)
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...