C++ 中串联二进制字符串的最大连续0
假设我们有一个长度为 n 的二进制字符串,给定另一个值 k。我们必须将二进制字符串连接 k 次。然后,我们必须在连接的字符串中找到连续 0 的最大数量。假设二进制字符串为“0010010”,k = 2,那么将字符串连接 k 次后,它将变为“00100100010010”。因此,连续 0 的最大数量为 3。
方法很简单。如果数字全部为 0,那么答案将为 n * k。如果字符串包含 1,则结果将是字符串子字符串的最大长度,包含所有 0,或者仅包含 0 的字符串的最大前缀的长度与仅包含 0 的字符串的最大后缀的长度之和。
算法
max_zero_count (str, n, k) −
Begin total := 0 len := 0 for i in range 0 to n, do if str[i] = 0, then increase len else len := 0 total := maximum of total and len done if total = n, then return n * k prefix := length of maximal prefix with only 0 suffix:= length of maximal suffix with only 0 if k > 1, then total := max of total, and (prefix + suffix) return total End
示例
#include <iostream> using namespace std; int max_length_substring(string str, int n, int k) { int total_len = 0; int len = 0; for (int i = 0; i < n; ++i) { if (str[i] == '0') //if the current character is 0, increase len len++; else len = 0; total_len = max(total_len, len); } if (total_len == n) //if the whole string has 0 only return n * k; int prefix = 0, suffix = 0; for (int i = 0; str[i] == '0'; ++i, ++prefix) //find length of maximal prefix with only 0; for (int i = n - 1; str[i] == '0'; --i, ++suffix) //find length of maximal suffix with only 0; if (k > 1) total_len = max(total_len, prefix + suffix); return total_len; } int main() { int k = 3; string str = "0010010"; int res = max_length_substring(str, str.length(), k); cout << "Maximum length of 0s: " << res; }
输出
Maximum length of 0s: 3
广告