给定一个长度为N的二进制字符串,我们需要找出该字符串的多少个子字符串仅包含1。
例子:
Input: S = “0110111”
Output: 9
Explanation:
There are 9 substring with only 1’s characters.
“1” comes 5 times.
“11” comes 3 times.
“111” comes 1 time.
Input: S = “000”
Output: 0
方法:想法是遍历二进制字符串并计算字符串的连续字符串。下面是该方法的说明:
- 从索引0到长度– 1遍历给定的二进制字符串
- 计算连续的“ 1”的数目,直到索引i。
- 对于每个新字符str [i],将有更多的子字符串,所有字符都为“ 1”
下面是上述方法的实现:
C++
// C++ implementation to find
// count of substring containing
// only ones
#include
using namespace std;
// Function to find the total number
// of substring having only ones
int countOfSubstringWithOnlyOnes(string s)
{
int res = 0, count = 0;
for (int i = 0; i < s.length(); i++) {
count = s[i] == '1' ? count + 1 : 0;
res = (res + count);
}
return res;
}
// Driver Code
int main()
{
string s = "0110111";
cout << countOfSubstringWithOnlyOnes(s)
<< endl;
return 0;
}
Java
// Java implementation to find
// count of substring containing
// only ones
class GFG{
// Function to find the total number
// of substring having only ones
static int countOfSubstringWithOnlyOnes(String s)
{
int res = 0, count = 0;
for(int i = 0; i < s.length(); i++)
{
count = s.charAt(i) == '1' ? count + 1 : 0;
res = (res + count);
}
return res;
}
// Driver code
public static void main(String[] args)
{
String s = "0110111";
System.out.println(countOfSubstringWithOnlyOnes(s));
}
}
// This code is contributed by dewantipandeydp
Python3
# Python3 implementation to find
# count of substring containing
# only ones
# Function to find the total number
# of substring having only ones
def countOfSubstringWithOnlyOnes(s):
count = 0
res = 0
for i in range(0,len(s)):
if s[i] == '1':
count = count + 1
else:
count = 0;
res = res + count
return res
# Driver Code
s = "0110111"
print(countOfSubstringWithOnlyOnes(s))
# This code is contributed by jojo9911
C#
// C# implementation to find count
// of substring containing only ones
using System;
class GFG{
// Function to find the total number
// of substring having only ones
static int countOfSubstringWithOnlyOnes(string s)
{
int res = 0, count = 0;
for(int i = 0; i < s.Length; i++)
{
count = s[i] == '1' ? count + 1 : 0;
res = (res + count);
}
return res;
}
// Driver code
public static void Main(string[] args)
{
string s = "0110111";
Console.Write(countOfSubstringWithOnlyOnes(s));
}
}
// This code is contributed by rutvik_56
输出
9