最大化给定二进制字符串中具有相同比例的 0 和 1 的分区
给定一个大小为N的二进制字符串S ,任务是找到字符串S的最大分区数,使得所有分区中0和1的数量之比相同。
例子:
Input: S = “010100001”
Output: 3
Explanation:
The substring [0, 2], [3, 5] and [6, 8] have the same ratio of ‘0′ and ‘1’ is 2:1. Therefore, the maximum possible partition is 3.
Input: str=”001101″
Output: 2
朴素方法:朴素方法是生成字符串S 的所有分区,并找到最大频率为0比1的分区。
时间复杂度: O(N*2 N )
辅助空间: O(N)
有效的方法:要解决这个问题,首先看一些观察:
Let say there are two prefix strings that obtain the same ratio of 0 and 1. Then it is possible to divide the larger prefix into two with the same ratio. For eg- S = “0101” the prefix [0, 1] has the ratio of 1:1 and the prefix[0, 3] has the ratio of 1:1 then it is possible to partition the string in two with the ratio 1:1. Therefore, just count the number of prefixes that has the same 0 and 1 ratio as that of string S and print the number of prefix with that ratio.
请按照以下步骤解决问题:
- 初始化两个整数变量,比如count_of_0和count_of_1为0 ,分别存储'0'和'1'字符的数量。
- 初始化一个哈希图,比如M ,它存储 ' 0'到 ' 1'的比率的频率。
- 使用变量i在[0, N-1]范围内迭代并执行以下步骤:
- 如果 S[i]等于'0'则将count_of_0增加1,否则将count_of_1增加1 。
- 找到count_of_0和count_of_1的 GCD 并将其存储在一个变量中,比如GCD 。
- 如果GCD = 0 ,则将m[{count_of_0, count_of_1}]增加1 。
- 如果GCD != 0 ,则将m[{count_of_0 / GCD, count_of_1 / GCD}]的值增加1 。
- 打印m[{count_of_0 / GCD, count_of_1 / GCD}]的值作为答案。
以下是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find maximum partition such
// that the ratio of 0 and 1 are same
void maximumPartition(string S)
{
// Size of string
int N = S.size();
// Variable to store the frequency
// of 0 and 1
int count_of_0 = 0, count_of_1 = 0;
// Map to store frequency of ratio
map, int> m;
int ans;
// Traverse the string
for (int i = 0; i < N; i++) {
// Increment the frequency
// of 0 by 1 if s[i] = 0
if (S[i] == '0')
count_of_0++;
// Otherwise increment frequency of 1
else
count_of_1++;
int first = count_of_0, second = count_of_1;
// Find GCD of count_of_0 and count_of_1
int GCD = __gcd(count_of_0, count_of_1);
// Convert the count of 0 and count of 1
// in the coprime numbers
if (GCD != 0) {
first = count_of_0 / GCD;
second = count_of_1 / GCD;
}
// Increase the ratio of 0 and 1 by 1
m[{ first, second }]++;
ans = m[{ first, second }];
}
cout << ans << endl;
}
// Driver Code
int main()
{
// Given Input
string S = "001101";
// Function Call
maximumPartition(S);
return 0;
}
2
时间复杂度: O(N log N)
辅助空间: O(N)