ログインしてください。
Official
C - C Stands for Center Editorial
by
C - C Stands for Center Editorial
by
physics0523
抜き出す部分文字列の真ん中にある C を固定して考えます。
\(S\) のうち \(i\) 文字目に C があるとき、その C が真ん中に来る部分文字列を数えます。
この C の左側には文字が \(i-1\) 個、右側には文字が \(|S|-i\) 個あります。
その結果、その C を真ん中とする文字列として、 C の左右それぞれに \(0,1,\dots,\min(i-1,|S|-i)\) 個文字を取り付けた、合計 \(\min(i,|S|-i+1)\) 個の文字列を得ることができます。
これを、 \(S\) 中に存在する文字 C 全てについて足し合わせるとこの問題に正解できます。
時間計算量は \(O(|S|)\) です。
実装例 (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:
