(好思路)找到一个字符串s中最长的子串,使得其中字符'A'和'B'的数量相等
我们关注的是'A'和'B'的数量差:
diff[i] = countA[i] - countB[i]。
如果diff[i] == diff[j],这意味着从j+1到i的子串中'A'和'B'的数量相等(因为差值抵消了)。
include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
string s;
cin >> s;
unordered_map<int, int> hash_map;
int countA = 0, countB = 0, max_len = 0;
hash_map[0] = -1; // 空串的差值为0,位置为-1
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'A') countA++;
else countB++;
int diff = countA - countB;
if (hash_map.find(diff) != hash_map.end()) {
max_len = max(max_len, i - hash_map[diff]);
} else {
hash_map[diff] = i;
}
}
cout << max_len << endl;
return 0;
}
浙公网安备 33010602011771号