길이가 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