检查二进制字符串是否包含连续的相同
给定一个由字符'0'和'1'组成的二进制字符串str 。任务是查找字符串是否有效。字符串只有在字符交替出现时才有效,即没有两个连续字符相同。
例子:
Input: str[] = “010101”
Output: Valid
Input: str[] = “010010”
Output: Invalid
方法:开始逐个字符遍历字符串,如果有任意两个连续的字符字符,则打印无效,否则最后打印有效。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true is str is valid
bool isValid(string str, int len)
{
// Assuming the string is binary
// If any two consecutive characters are equal
// then the string is invalid
for (int i = 1; i < len; i++) {
if (str[i] == str[i - 1])
return false;
}
// If the string is alternating
return true;
}
// Driver code
int main()
{
string str = "0110";
int len = str.length();
if (isValid(str, len))
cout << "Valid";
else
cout << "Invalid";
return 0;
}
Java
// Java implementation of the approach
class gfg
{
// Function that returns true is str is valid
static boolean isValid(String str, int len)
{
// Assuming the string is binary
// If any two consecutive
// characters are equal
// then the string is invalid
for (int i = 1; i < len; i++)
{
if (str.charAt(i) == str.charAt(i - 1))
return false;
}
// If the string is alternating
return true;
}
// Driver code
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");
}
}
// This code is Contributed by Code_Mech
Python3
# Python3 implementation of the approach
# Function that returns true is str is valid
def isValid(string, length):
# Assuming the string is binary
# If any two consecutive characters
# are equal then the string is invalid
for i in range(1, length):
if string[i] == string[i - 1]:
return False
# If the string is alternating
return True
# Driver code
if __name__ == "__main__":
string = "0110"
length = len(string)
if isValid(string, length):
print("Valid")
else:
print("Invalid")
# This code is contributed by Rituraj Jain
C#
// C# implementation of the approach
using System;
class gfg
{
// Function that returns true is str is valid
static bool isValid(string str, int len)
{
// Assuming the string is binary
// If any two consecutive
// characters are equal
// then the string is invalid
for (int i = 1; i < len; i++)
{
if (str[i] == str[i - 1])
return false;
}
// If the string is alternating
return true;
}
// Driver code
public static void Main()
{
string str = "0110";
int len = str.Length;
if (isValid(str, len))
Console.Write("Valid");
else
Console.Write("Invalid");
}
}
// This code is contributed by Ita_c.
PHP
Javascript
输出:
Invalid