📌  相关文章
📜  给定二进制字符串中所有字符相同的子字符串的计数

📅  最后修改于: 2021-05-17 21:56:18             🧑  作者: Mango

给定二进制字符串str仅包含01 ,任务是查找分别仅包含10的子字符串的数量,即所有字符相同。

例子:

天真的方法:这个想法是生成给定字符串的所有可能的子字符串。对于每个子串检查如果字符串包含全部为1或全部为0。如果是,则计算该子字符串。完成上述操作后,打印子字符串的计数。

时间复杂度:O(N 3 )
辅助空间:O(N)

高效的方法:想法是使用滑动窗口和两个指针方法的概念。以下是查找仅包含1的子字符串计数的步骤:

  1. 初始化两个指针,即LR ,并将它们初始化为0
  2. 现在,在给定的字符串进行迭代,并检查当前字符是否等于1。如果是,则通过增加R的值来扩展窗口。
  3. 如果当前字符为0 ,则窗口L到R – 1包含全1。
  4. L的子字符串数加到R – 1到答案为((R – L)*(R – L + 1))/ 2上,并递增R并将L重新初始化为R。
  5. 重复该过程,直到L和R彼此交叉。
  6. 步骤4中打印所有子字符串的计数。
  7. 要计数全为0的子字符串的数量,请翻转给定的字符串,即,全0将被转换为1 ,反之亦然。
  8. 翻转后的字符串中的字符1重复从步骤1到步骤4的上述步骤,以获取其中仅包含0的子字符串的计数并打印该计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count number of
// sub-strings of a given binary
// string that contains only 1
int countSubAllOnes(string s)
{
    int l = 0, r = 0, ans = 0;
 
    // Iterate untill L and R cross
    // each other
    while (l <= r) {
 
        // Check if reached the end
        // of string
        if (r == s.length()) {
            ans += ((r - l) * (r - l + 1)) / 2;
            break;
        }
 
        // Check if encountered '1'
        // then extend window
        if (s[r] == '1')
            r++;
 
        // Check if encountered '0' then
        // add number of strings of
        // current window and change the
        // values for both l and r
        else {
 
            ans += ((r - l) * (r - l + 1)) / 2;
            l = r + 1;
            r++;
        }
    }
 
    // Return the answer
    return ans;
}
 
// Function to flip the bits of string
void flip(string& s)
{
 
    for (int i = 0; s[i]; i++) {
        if (s[i] == '1')
            s[i] = '0';
        else
            s[i] = '1';
    }
  cout<


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count number of
// sub-Strings of a given binary
// String that contains only 1
static int countSubAllOnes(String s)
{
    int l = 0, r = 0, ans = 0;
 
    // Iterate untill L and R cross
    // each other
    while (l <= r)
    {
         
        // Check if reached the end
        // of String
        if (r == s.length())
        {
            ans += ((r - l) * (r - l + 1)) / 2;
            break;
        }
 
        // Check if encountered '1'
        // then extend window
        if (s.charAt(r) == '1')
            r++;
 
        // Check if encountered '0' then
        // add number of Strings of
        // current window and change the
        // values for both l and r
        else
        {
            ans += ((r - l) * (r - l + 1)) / 2;
            l = r + 1;
            r++;
        }
    }
 
    // Return the answer
    return ans;
}
 
// Function to flip the bits of String
static String flip(char []s)
{
    for(int i = 0; i < s.length; i++)
    {
        if (s[i] == '1')
            s[i] = '0';
        else
            s[i] = '1';
    }
    return String.valueOf(s);
}
 
// Function to count number of
// sub-Strings of a given binary
// String that contains only 0s & 1s
static int countSubAllZerosOnes(String s)
{
 
    // count of subString
    // which contains only 1s
    int only_1s = countSubAllOnes(s);
 
    // Flip the character of String s
    // 0 to 1 and 1 to 0 to count the
    // subString with consecutive 0s
    s = flip(s.toCharArray());
 
    // count of subString
    // which contains only 0s
    int only_0s = countSubAllOnes(s);
 
    return only_0s + only_1s;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String str
    String s = "011";
 
    // Function call
    System.out.print(countSubAllZerosOnes(s) + "\n");
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program for
# the above approach
 
# Function to count number of
# sub-strings of a given binary
# string that contains only 1
def countSubAllOnes(s):
   
    l, r, ans = 0, 0, 0
 
    # Iterate untill L and R cross
    # each other
    while (l <= r):
 
        # Check if reached the end
        # of string
        if (r == len(s)):
            ans += ((r - l) *
                    (r - l + 1)) // 2
            break
        
        # Check if encountered '1'
        # then extend window
        if (s[r] == '1'):
            r += 1
 
        # Check if encountered '0' then
        # add number of strings of
        # current window and change the
        # values for both l and r
        else :
            ans += ((r - l) *
                    (r - l + 1)) // 2
            l = r + 1
            r += 1
 
    # Return the answer
    return ans
 
# Function to flip the bits of string
def flip(s):
      
    arr = list(s)
    for i in range (len(s)):
        if (arr[i] == '1'):
            arr[i] = '0'
        else:
            arr[i] = '1'
    s = ''.join(arr)
    return s
 
# Function to count number of
# sub-strings of a given binary
# string that contains only 0s & 1s
def countSubAllZerosOnes(s):
 
    # count of substring
    # which contains only 1s
    only_1s = countSubAllOnes(s)
 
    # Flip the character of string s
    # 0 to 1 and 1 to 0 to count the
    # substring with consecutive 0s
    s = flip(s)
 
    # count of substring
    # which contains only 0s
    only_0s = countSubAllOnes(s)
 
    return only_0s + only_1s
 
# Driver Code
if __name__ == "__main__":
   
    # Given string str
    s  = "011"
 
    # Function Call
    print (countSubAllZerosOnes(s))
    
# This code is contributed by Chitranayal


C#
// C# program for the above approach
using System;
class GFG{
 
// Function to count number of
// sub-Strings of a given binary
// String that contains only 1
static int countSubAllOnes(String s)
{
    int l = 0, r = 0, ans = 0;
 
    // Iterate untill L and R cross
    // each other
    while (l <= r)
    {
         
        // Check if reached the end
        // of String
        if (r == s.Length)
        {
            ans += ((r - l) * (r - l + 1)) / 2;
            break;
        }
 
        // Check if encountered '1'
        // then extend window
        if (s[r] == '1')
            r++;
 
        // Check if encountered '0' then
        // add number of Strings of
        // current window and change the
        // values for both l and r
        else
        {
            ans += ((r - l) * (r - l + 1)) / 2;
            l = r + 1;
            r++;
        }
    }
 
    // Return the answer
    return ans;
}
 
// Function to flip the bits of String
static String flip(char []s)
{
    for(int i = 0; i < s.Length; i++)
    {
        if (s[i] == '1')
            s[i] = '0';
        else
            s[i] = '1';
    }
    return String.Join("",s);
}
 
// Function to count number of
// sub-Strings of a given binary
// String that contains only 0s & 1s
static int countSubAllZerosOnes(String s)
{
 
    // count of subString
    // which contains only 1s
    int only_1s = countSubAllOnes(s);
 
    // Flip the character of String s
    // 0 to 1 and 1 to 0 to count the
    // subString with consecutive 0s
    s = flip(s.ToCharArray());
 
    // count of subString
    // which contains only 0s
    int only_0s = countSubAllOnes(s);
 
    return only_0s + only_1s;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String str
    String s = "011";
 
    // Function call
    Console.Write(countSubAllZerosOnes(s) + "\n");
}
}
 
// This code is contributed by Rohit_ranjan


输出:
4






时间复杂度: O(N),其中N是给定字符串的长度。
辅助空间: O(1)