给定一个二进制字符串S,该任务是计数总二进制字符串由至少一个“1”的长度的后反复去除子串“10”的所有出现等于给定的字符串的长度,“00”,从给定的字符串.
例子:
Input: S = “111”
Output: 7
Explanation: Since there are no occurrences of “10” or “01” in the given string, length of the remaining string is 3. All possible binary strings of length 3 consisting of at least one set bit are {“001”, “010”, “011”, “100”, “101”, “110”, “111”}
Input: S = “0101”
Output: 3
Explanation: After deleting “10”, S = “01”. Therefore, length of remaining string is 2. Strings of length 2 consisting of at least one set bit are {“01”, “10”, “11”}
方法:这个想法是在从中删除所有形式为“10”和“00”的子字符串后计算给定字符串的长度。考虑剩下的;字符串的长度为N ,则由至少一个设置位组成的字符串总数将等于2 N -1 。
请按照以下步骤解决问题:
- 初始化一个变量,比如count 。
- 迭代字符串S的字符。对于每个字符,检查它是否为‘0’并且计数是否大于0 。如果发现为真,则将计数减1 。
- 否则,如果当前字符为‘1’ ,则将count增加1 。
- 完全遍历字符串,打印2 count – 1作为所需答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count the strings
// consisting of at least 1 set bit
void countString(string S)
{
// Initialize count
long long count = 0;
// Iterate through string
for (auto it : S) {
if (it == '0' and count > 0) {
count--;
}
else {
count++;
}
}
// The answer is 2^N-1
cout << ((1 << count) - 1) << "\n";
}
// Driver Code
int main()
{
// Given string
string S = "1001";
// Function call
countString(S);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count the strings
// consisting of at least 1 set bit
static void countString(String S)
{
// Initialize count
int count = 0;
// Iterate through string
for(char it : S.toCharArray())
{
if (it == '0' && count > 0)
{
count--;
}
else
{
count++;
}
}
// The answer is 2^N-1
System.out.print((1 << count) - 1);
}
// Driver Code
public static void main(String[] args)
{
// Given string
String S = "1001";
// Function call
countString(S);
}
}
// This code is contributed by susmitakundugoaldanga
Python3
# Python3 program for the
# above approach
# Function to count the
# strings consisting of
# at least 1 set bit
def countString(S):
# Initialize count
count = 0
# Iterate through
# string
for i in S:
if (i == '0' and
count > 0):
count -= 1
else:
count += 1
# The answer is 2^N-1
print((1 << count) - 1)
# Driver Code
if __name__ == "__main__":
# Given string
S = "1001"
# Function call
countString(S)
# This code is contributed by Virusbuddah_
C#
// C# program for the above approach
using System;
class GFG{
// Function to count the strings
// consisting of at least 1 set bit
static void countString(string S)
{
// Initialize count
int count = 0;
// Iterate through string
foreach(char it in S)
{
if (it == '0' && count > 0)
{
count--;
}
else
{
count++;
}
}
// The answer is 2^N-1
Console.Write((1 << count) - 1);
}
// Driver Code
public static void Main(string[] args)
{
// Given string
string S = "1001";
// Function call
countString(S);
}
}
// This code is contributed by chitranayal
Javascript
3
时间复杂度: O(L) 其中 L 是字符串的长度。
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live