C ++中带有大于b的前缀
在此问题中,我们为字符串str提供仅包含a和b以及整数N的值,从而通过将strn次附加来创建字符串。我们的任务是打印子串的总数,其中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将根据前缀以及a和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