📌  相关文章
📜  仅包含 1 的二进制字符串的子字符串计数

📅  最后修改于: 2021-09-07 05:21:53             🧑  作者: Mango

给定一个长度为N的二进制字符串,我们需要找出这个字符串有多少个子字符串只包含 1。

例子:

方法:我们的想法是遍历二进制字符串和计数字符串中的连续的。下面是该方法的说明:

  • 遍历给定的二进制字符串从索引 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


Javascript


输出
9

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live