bluecode-字符串'chhc'子串权值求和

27 阅读1分钟

问题描述

小M正在研究一个由字母'c''h'组成的字符串,他的任务是计算该字符串所有子串中,出现的子串"chhc"的总次数。我们定义一个字符串的权值为其包含"chhc"子串的数量。你的任务是帮助小M求出整个字符串中所有子串的权值之和。


测试样例

样例1:

输入:s = "chhchhc"
输出:8

样例2:

输入:s = "chhcchhcchhc"
输出:43

样例3:

输入:s = "hhhh"
输出:0

#include <iostream>
#include <string>
#include <vector>

using namespace std;
int solution(string s) {
  int n = s.length();
  long long total_count = 0;
  for (int i = 0; i <= n - 4; i++) {
    if (s.substr(i, 4) == "chhc") {
      total_count += static_cast<long long>(i + 1) * (n - i - 3);
    }
  }
  return total_count;
}

int main() {
  cout << (solution("chhchhc") == 8) << endl;
  cout << (solution("chhcchhcchhc") == 43) << endl;
  cout << (solution("hhhh") == 0) << endl;
  return 0;
}