题解 | 字符串子串
字符串子串
https://www.nowcoder.com/practice/51aac67b554b4c00b68406f53b6f3519
void solve() {
string s; cin >> s;
int n = s.length(), ans = 0;
auto cal = [&](const string& s) -> int {
int n = s.length(), ans = 0;
int cntr = 0, cnte = 0;
int r = 0;
for(int l = 0; l < n; ++l) {
while(r < n && (cntr == 0 || cnte == 0)) {
if(s[r] == 'r') cntr++;
if(s[r] == 'e') cnte++;
r++;
}
if(cntr > 0 && cnte > 0) ans += (n - r + 1); // 如果已经满足条件了,那么往右延申的字串一定也符合条件
if(s[l] == 'r') cntr--;
if(s[l] == 'e') cnte--;
}
return ans;
};
int sum = 0;
string t = "";
for(char c : s) {
if(c == 'd') {
if(!t.empty()) sum += cal(t);
t = ""; // 切割字符串
} else {
t += c;
}
}
if(!t.empty()) sum += cal(t); // 处理尾巴
cout << sum << endl;
}
