이 문제에서는 a와 b만 포함하는 문자열 str과 str을 n번 추가하여 문자열이 생성되도록 정수 N이 제공됩니다. 우리의 임무는 a의 개수가 b의 개수보다 많은 부분 문자열의 총 개수를 출력하는 것입니다.
문제를 이해하기 위해 예를 들어보겠습니다.
Input: aab 2 Output: 9 Explanation: created string is aabaab. Substrings with count(a) > count(b) : ‘a’ , ‘aa’, ‘aab’, ‘aaba’, ‘aabaa’, ‘aabaab’, ‘aba’, ‘baa’, ‘abaa’.
이 문제를 해결하려면 문자열에 필요한 접두사 하위 집합이 포함되어 있는지 확인해야 합니다. 여기서는 정식 버전이 아닌 문자열 str을 확인합니다. 여기서 w는 접두사와 b의 발생 횟수를 기반으로 문자열을 확인합니다.
이 프로그램은 솔루션 구현을 보여줍니다.
예
#include <iostream>
#include <string.h>
using namespace std;
int prefixCount(string str, int n){
int a = 0, b = 0, count = 0;
int i = 0;
int len = str.size();
for (i = 0; i < len; i++) {
if (str[i] == 'a')
a++;
if (str[i] == 'b')
b++;
if (a > b) {
count++;
}
}
if (count == 0 || n == 1) {
cout<<count;
return 0;
}
if (count == len || a - b == 0) {
cout<<(count*n);
return 0;
}
int n2 = n - 1, count2 = 0;
while (n2 != 0) {
for (i = 0; i < len; i++) {
if (str[i] == 'a')
a++;
if (str[i] == 'b')
b++;
if (a > b)
count2++;
}
count += count2;
n2--;
if (count2 == 0)
break;
if (count2 == len) {
count += (n2 * count2);
break;
}
count2 = 0;
}
return count;
}
int main() {
string str = "aba";
int N = 2;
cout<<"The string created by using '"<<str<<"' "<<N<<" times has ";
cout<<prefixCount(str, N)<<" substring with count of a greater than count of b";
return 0;
} 출력
The string created by using 'aba' 2 times has 5 substring with count of a greater than count of b