Official

C - C Stands for Center Editorial by en_translator


Fix the C at the center of an extracted string.
If the \(i\)-th character of \(S\) is C, we count how many substrings have that C as the middle.
To the left and right of this C are \((i-1)\) characters each.
With \(0,1,\dots,\min(i-1,|S|-i)\) characters to the left and right of that C, we can obtain a total of \(\min(i,|S|-i+1)\) strings with C at the middle.
All that left is to sum them up for all C in \(S\).

The time complexity is \(O(|S|)\).

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;
using ll=long long;

int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  string s;
  cin >> s;
  ll l=s.size();
  ll res=0;
  for(ll i=0;i<l;i++){
    if(s[i]=='C'){
      res+=min(i+1,l-i);
    }
  }
  cout << res << "\n";
  return 0;
}

posted:
last update: