给定字符串最多包含 X 个 0 和 Y 个 1 的最长子字符串
给定一个长度为N的二进制字符串S ,任务是找到最多包含X个0和Y个1 的最长子串。
例子:
Input: S = “10101”, N = 5, X = 1, Y = 2
Output: 3
Explanation: The longest substring with at most 1 zero and 2 ones is “101” with length 3.
Input: S = “111”, N = 3, X = 1, Y = 1
Output: 1
Explanation: longest substring with at most 1 zero and 1 one is “1” with length 1.
Input: S = “00000”, N = 5, X = 0, Y = 1
Output: 0
Explanation: No substrings exists with at most 0 number of zero’s and 1 number of one’s as whole string does not contain 1’s anywhere.
朴素方法:解决这个问题的朴素方法是找到所有子字符串,并为每个子字符串计算子字符串中0和1 的数量,并检查它们的数量是否分别最多为 X 和 Y。
时间复杂度: O(N 2 )
辅助空间: O(1)
Efficient Approach:这个问题可以使用基于以下思想的两个指针方法的概念来解决:
Use two pointers (i, j), Where j is the last pointer and i is the starting pointer. Use those pointers to keep track of number of 0s and 1s in that range and update those based on the count of 0s and 1s in that range to adjust the substring length.
- Increment the last pointer till the any one of the count of 0s and 1s does not exceed their upper limit.
- If any of their count exceeds the provided limit then increment the first pointer to decrease the range.
- The longest range will give the longest substring.
请按照以下步骤解决此问题。
- 将i、j和maxLength初始化为0 。
- 当j < N时遍历。
- 计算在第 j 个索引处结束的0和1 的数量。
- 检查0和1 的数量是否满足给定条件。
- 如果是,则计算从i开始到j结束的当前子字符串的大小。
- 如果计算的大小大于maxLength ,则更新maxLength 。
- 否则,减少第 i 个索引处的字符数并增加i的值。
- 返回maxLength作为最终答案。
下面是上述方法的实现:
C++14
// C++ code to implement the approach
#include
using namespace std;
// Function to find the longest substring
// with at most X number of 0's
// and Y number of 1's
int longestKSubarray(string& S, int X, int Y)
{
int N = S.length(), i = 0, j = 0;
int count0 = 0, count1 = 0, maxLength = 0;
while (j < N) {
// Increment the count of jth character
if (S[j] == '0') {
count0++;
}
else {
count1++;
}
// Check for Given condition
if (count0 > X || count1 > Y) {
// Reduce the count of ith charater
if (S[i] == '0') {
count0--;
}
else {
count1--;
}
// Move the ith pointer
i++;
}
// Move the jth pointer
j++;
// Keep Updating the maxLength.
maxLength = max(maxLength, j - i);
}
return maxLength;
}
// Driver's code
int main()
{
string S = "10101";
int X = 1, Y = 2;
// Function call
cout << longestKSubarray(S, X, Y);
return 0;
}
Javascript
3
时间复杂度: 在)
辅助空间: O(1)