📌  相关文章
📜  给定二进制字符串中交替子字符串的数量

📅  最后修改于: 2021-09-17 07:23:19             🧑  作者: Mango

给定一个大小为N的二进制字符串,任务是计算字符串S中出现的交替子字符串的数量。

例子:

朴素的方法:解决这个问题的最简单的方法是 首先,找到字符串S 的所有子字符串,然后检查每个字符串是否交替。

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

高效方法:这个问题具有重叠子问题属性和最优子结构属性。所以这个问题可以用动态规划解决。请按照以下步骤解决此问题:

  • 声明一个dp数组,其中dp[i][j]存储以 char i开头且在[j, N-1]范围内的交替字符串的数量。
  • 使用变量i在范围[N-1, 0] 中迭代并执行以下步骤:
    • 如果i等于N-1 ,则如果当前字符为‘1’ ,则将1分配给dp[1][i] ,否则将1分配给dp[0][i]
    • 否则,如果当前字符为‘0’ ,则将dp[0][i]更新为1+dp[1][i+1] ,否则将dp[1][i]更新为1+dp[0][我+1]。
  • 将变量 say ans初始化为0以存储交替的子串的数量。
  • 使用变量i在范围[0, N-1] 中迭代并执行以下步骤:
    • ans更新为dp[0][i]dp[1][i] 的最大值
  • 最后,打印ans 中得到的值作为答案。

下面是上述方法的实现:

C++
// c++ program for the above approach
 
#include 
using namespace std;
 
// Function to count number of alternating
// substrings from a given binary string
int countAlternatingSubstrings(string S, int N)
{
    // Initialize dp array, where dp[i][j] stores
    // the number of alternating strings starts
    // with i and having j elements.
    vector > dp(2, vector(N, 0));
 
    // Traverse the string from the end
    for (int i = N - 1; i >= 0; i--) {
 
        // If i is equal to N - 1
        if (i == N - 1) {
 
            if (S[i] == '1')
                dp[1][i] = 1;
 
            else
                dp[0][i] = 1;
        }
        // Otherwise,
        else {
 
            // Increment count of
            // substrings starting at i
            // and has 0 in the beginning
            if (S[i] == '0')
                dp[0][i] = 1 + dp[1][i + 1];
 
            // Increment count of
            // substrings starting at i
            // and has 1 in the beginning
            else
                dp[1][i] = 1 + dp[0][i + 1];
        }
    }
    // Stores the result
    int ans = 0;
 
    // Iterate in the range [0, N-1]
    for (int i = 0; i < N; i++) {
 
        // Update ans
        ans += max(dp[0][i], dp[1][i]);
    }
 
    // Return the ans
    return ans;
}
 
// Driver code
int main()
{
    // Given Input
    string S = "0010";
    int N = S.length();
 
    // Function call
    cout << countAlternatingSubstrings(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count number of alternating
// substrings from a given binary string
static int countAlternatingSubstrings(String S, int N)
{
     
    // Initialize dp array, where dp[i][j] stores
    // the number of alternating strings starts
    // with i and having j elements.
    int[][] dp = new int[2][N];
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < N; j++)
        {
            dp[i][j] = 0;
        }
    }
 
    // Traverse the string from the end
    for(int i = N - 1; i >= 0; i--)
    {
         
        // If i is equal to N - 1
        if (i == N - 1)
        {
            if (S.charAt(i) == '1')
                dp[1][i] = 1;
 
            else
                dp[0][i] = 1;
        }
         
        // Otherwise,
        else
        {
             
            // Increment count of
            // substrings starting at i
            // and has 0 in the beginning
            if (S.charAt(i) == '0')
                dp[0][i] = 1 + dp[1][i + 1];
 
            // Increment count of
            // substrings starting at i
            // and has 1 in the beginning
            else
                dp[1][i] = 1 + dp[0][i + 1];
        }
    }
     
    // Stores the result
    int ans = 0;
 
    // Iterate in the range [0, N-1]
    for(int i = 0; i < N; i++)
    {
         
        // Update ans
        ans += Math.max(dp[0][i], dp[1][i]);
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Input
    String S = "0010";
    int N = S.length();
     
    // Function call
    System.out.print(countAlternatingSubstrings(S, N));
}
}
 
// This code is contributed by sanjoy_62


Python3
# Python3 program for the above approach
 
# Function to count number of alternating
# substrings from a given binary string
def countAlternatingSubstrings(S, N):
     
    # Initialize dp array, where dp[i][j] stores
    # the number of alternating strings starts
    # with i and having j elements.
    dp = [[0 for i in range(N)]
             for i in range(2)]
 
    # Traverse the string from the end
    for i in range(N - 1, -1, -1):
         
        # If i is equal to N - 1
        if (i == N - 1):
 
            if (S[i] == '1'):
                dp[1][i] = 1
            else:
                dp[0][i] = 1
                 
        # Otherwise,
        else:
 
            # Increment count of
            # substrings starting at i
            # and has 0 in the beginning
            if (S[i] == '0'):
                dp[0][i] = 1 + dp[1][i + 1]
 
            # Increment count of
            # substrings starting at i
            # and has 1 in the beginning
            else:
                dp[1][i] = 1 + dp[0][i + 1]
                 
    # Stores the result
    ans = 0
 
    # Iterate in the range [0, N-1]
    for i in range(N):
         
        # Update ans
        ans += max(dp[0][i], dp[1][i])
 
    # Return the ans
    return ans
 
# Driver code
if __name__ == '__main__':
     
    # Given Input
    S = "0010"
    N = len(S)
 
    # Function call
    print (countAlternatingSubstrings(S, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to count number of alternating
// substrings from a given binary string
static int countAlternatingSubstrings(string S, int N)
{
     
    // Initialize dp array, where dp[i][j] stores
    // the number of alternating strings starts
    // with i and having j elements.
    int[,] dp = new int[2, N];
    for(int i = 0; i < 2; i++)
    {
        for(int j = 0; j < N; j++)
        {
            dp[i, j] = 0;
        }
    }
 
    // Traverse the string from the end
    for(int i = N - 1; i >= 0; i--)
    {
         
        // If i is equal to N - 1
        if (i == N - 1)
        {
            if (S[i] == '1')
                dp[1, i] = 1;
 
            else
                dp[0, i] = 1;
        }
         
        // Otherwise,
        else
        {
             
            // Increment count of
            // substrings starting at i
            // and has 0 in the beginning
            if (S[i] == '0')
                dp[0, i] = 1 + dp[1, i + 1];
 
            // Increment count of
            // substrings starting at i
            // and has 1 in the beginning
            else
                dp[1, i] = 1 + dp[0, i + 1];
        }
    }
     
    // Stores the result
    int ans = 0;
 
    // Iterate in the range [0, N-1]
    for(int i = 0; i < N; i++)
    {
         
        // Update ans
        ans += Math.Max(dp[0, i], dp[1, i]);
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
public static void Main()
{
   
    // Given Input
    string S = "0010";
    int N = S.Length;
     
    // Function call
    Console.Write(countAlternatingSubstrings(S, N));
}
}
 
// This code is contributed by target_2.


Javascript


输出:
7

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