C++ 中 a 比 b 更多的前缀
在这个问题中,我们给定一个仅包含 a 和 b 的字符串 str 和一个整数 N,其中通过将 str 重复 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 而不是完整版本。在这里,我们将根据前缀和 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP