Check if a binary string contains consecutive same or not
Last Updated :
06 Dec, 2022
Given a binary string str consisting of characters ‘0’ and ‘1’. The task is to find whether the string is valid or not. A string is valid only if the characters are alternating i.e. no two consecutive characters are the same.
Examples:
Input: str[] = “010101”
Output: Valid
Input: str[] = “010010”
Output: Invalid
Approach: Start traversing the string character by character and if there are any two consecutive characters that are equal then print Invalid else print Valid in the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isValid(string str, int len)
{
for ( int i = 1; i < len; i++) {
if (str[i] == str[i - 1])
return false ;
}
return true ;
}
int main()
{
string str = "0110" ;
int len = str.length();
if (isValid(str, len))
cout << "Valid" ;
else
cout << "Invalid" ;
return 0;
}
|
Java
class gfg
{
static boolean isValid(String str, int len)
{
for ( int i = 1 ; i < len; i++)
{
if (str.charAt(i) == str.charAt(i - 1 ))
return false ;
}
return true ;
}
public static void main(String[] args)
{
String str = "0110" ;
int len = str.length();
if (isValid(str, len))
System.out.println( "Valid" );
else
System.out.println( "Invalid" );
}
}
|
Python3
def isValid(string, length):
for i in range ( 1 , length):
if string[i] = = string[i - 1 ]:
return False
return True
if __name__ = = "__main__" :
string = "0110"
length = len (string)
if isValid(string, length):
print ( "Valid" )
else :
print ( "Invalid" )
|
C#
using System;
class gfg
{
static bool isValid( string str, int len)
{
for ( int i = 1; i < len; i++)
{
if (str[i] == str[i - 1])
return false ;
}
return true ;
}
public static void Main()
{
string str = "0110" ;
int len = str.Length;
if (isValid(str, len))
Console.Write( "Valid" );
else
Console.Write( "Invalid" );
}
}
|
PHP
<?php
function isValid( $str , $len )
{
for ( $i = 1; $i < $len ; $i ++)
{
if ( $str [ $i ] == $str [ $i - 1])
return false;
}
return true;
}
$str = "0110" ;
$len = strlen ( $str );
if (isValid( $str , $len ))
echo "Valid" ;
else
echo "Invalid" ;
?>
|
Javascript
<script>
function isValid(str,len)
{
for (let i = 1; i < len; i++)
{
if (str[i] == str[i - 1])
return false ;
}
return true ;
}
let str = "0110" ;
let len = str.length;
if (isValid(str, len))
document.write( "Valid" );
else
document.write( "Invalid" );
</script>
|
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...