#include <bits/stdc++.h>
using namespace std;
inline long long int random(long long int _min, long long int _max) {
  static bool first = true;
  if (first) {
    srand(time(NULL));
    first = false;
  }
  return _min + rand() % ((_max + 1) - _min);
}
template <class T>
inline bool read(T &x) {
  long long int c = getchar();
  long long int sgn = 1;
  while (~c && c < '0' || c > '9') {
    if (c == '-') sgn = -1;
    c = getchar();
  }
  for (x = 0; ~c && '0' <= c && c <= '9'; c = getchar()) x = x * 10 + c - '0';
  x *= sgn;
  return ~c;
}
inline long long int exp(long long int a, long long int b) {
  a %= 1000000007;
  long long int res = 1;
  while (b > 0) {
    if (b & 1) {
      res = res * a % 1000000007;
    }
    a = a * a % 1000000007;
    b >>= 1;
  }
  return res;
}
inline long long int add(long long int a, long long int b) {
  a += b;
  if (a >= 1000000007) a -= 1000000007;
  return a;
}
inline long long int sub(long long int a, long long int b) {
  a -= b;
  if (a < 0) a += 1000000007;
  return a;
}
inline long long int multi(long long int a, long long int b) {
  a *= b;
  if (a >= 1000000007) a %= 1000000007;
  return a;
}
inline long long int on_bit(long long int N, long long int pos) {
  return N = N | (1 << pos);
}
inline long long int off_bit(long long int N, long long int pos) {
  return N = N & ~(1 << pos);
}
inline bool check_bit(long long int N, long long int pos) {
  return (bool)(N & (1 << pos));
}
bool possible(char a, char b) {
  if ((a == 'A' && b == 'B') || (a == 'B' && b == 'B')) return 1;
  return 0;
}
int main() {
  long long int ___T;
  cin >> ___T;
  for (long long int cs = 1; cs <= ___T; cs++) {
    string s;
    cin >> s;
    int i = 0, cnt = 0;
    deque<int> idx;
    while (i < s.size()) {
      if (idx.size()) {
        bool flg = 0;
        int lo = idx.back(), hi = i;
        while (lo >= 0 && hi < s.size() && possible(s[lo], s[hi])) {
          s[lo] = s[hi] = '0';
          lo--;
          hi++;
          cnt += 2;
          flg = 1;
        }
        if (flg) {
          i = hi;
          idx.pop_back();
          if (lo >= 0 && s[lo] != '0') idx.push_back(lo);
          continue;
        }
      }
      if (i + 1 < s.size() && possible(s[i], s[i + 1])) {
        s[i] = s[i + 1] = '0';
        cnt += 2;
        int lo = i - 1, hi = i + 2;
        while (lo >= 0 && hi < s.size() && possible(s[lo], s[hi])) {
          s[lo] = s[hi] = '0';
          lo--;
          hi++;
          cnt += 2;
        }
        i = hi;
        if (lo >= 0 && s[lo] != '0') idx.push_back(lo);
      } else
        i++;
    }
    cout << s.size() - cnt << "\n";
  }
  return 0;
}
