fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6. int tc;
  7. cin >> tc;
  8.  
  9. while (tc--) {
  10. int n;
  11. cin >> n;
  12. string s;
  13. cin >> s;
  14.  
  15. int cA = 0, cB = 0;
  16. for (char c : s) {
  17. if (c == 'a') cA++;
  18. else cB++;
  19. }
  20.  
  21. int d = cB - cA;
  22.  
  23. if (d == 0) {
  24. cout << 0 << "\n";
  25. continue;
  26. }
  27.  
  28. vector<int> a(n);
  29. for (int i = 0; i < n; i++) {
  30. a[i] = (s[i] == 'a') ? -1 : 1;
  31. }
  32.  
  33. int pref = 0;
  34. int ans = INT_MAX;
  35. unordered_map<int, int> mp;
  36. mp[pref] = -1;
  37.  
  38. for (int i = 0; i < n; i++) {
  39. pref += a[i];
  40. int complement = pref - d;
  41.  
  42. if (mp.find(complement) != mp.end()) {
  43. ans = min(ans, i - mp[complement]);
  44. }
  45.  
  46. mp[pref] = i;
  47. }
  48.  
  49. if (ans == n || ans == INT_MAX)
  50. cout << -1 << "\n";
  51. else
  52. cout << ans << "\n";
  53. }
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0s 5308KB
stdin
5
5
bbbab
6
bbaaba
4
aaaa
12
aabbaaabbaab
5
aabaa
stdout
3
0
-1
2
-1