// created time: 2026-03-19 14:39:14
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define fi first
#define se second
#define mkp make_pair
#define pb emplace_back
#define popcnt __builtin_popcountll
const int mod = 998244353;
inline ll read(){
ll x=0, f=1; int ch=getchar();
while(ch<'0' || ch>'9') { if(ch=='-') f=-1; ch=getchar(); }
while(ch>='0' && ch<='9') x=x*10+ch-'0', ch=getchar();
return x*f;
}
inline int lg2(int x){ return 31^__builtin_clz(x); }
inline ll lg2(ll x){ return 63^__builtin_clzll(x); }
inline void addmod(int &x){ if(x >= mod) x -= mod; }
inline void addmod(ll &x){ if(x >= mod) x -= mod; }
inline ll qpow(ll a,ll b){
ll ans=1, base=a;
while(b){
if(b&1) ans=ans*base%mod;
base=base*base%mod; b>>=1;
}
return ans;
}
inline ll INV(ll x){ return qpow(x, mod-2); }
int n,qz[1000005]; char s[1000005];
int dp[1000005],fk[3000005][2];
void procedure(){
scanf("%s",s+1); n=strlen(s+1);
qz[0]=n;
for(int i=1;i<=n;i++) qz[i]=qz[i-1]+(s[i]=='B'?2:-1);
dp[0]=0;
for(int i=0;i<=3*n;i++)fk[i][0]=fk[i][1]=1e9;
fk[qz[0]][s[1]=='B']=0;
for(int i=1;i<=n;i++){
if(s[i]=='A') dp[i]=fk[qz[i]][1];
else dp[i]=min(fk[qz[i]][0],fk[qz[i]][1]);
dp[i]=min(dp[i],dp[i-1]+1);
fk[qz[i]][s[i+1]=='B']=min(fk[qz[i]][s[i+1]=='B'],dp[i]);
}
printf("%d\n",(n-dp[n])/3);
}
int main(){
#ifdef LOCAL
assert(freopen("test.in","r",stdin));
assert(freopen("test.out","w",stdout));
#endif
ll T=read();
// math_init();
while(T--) procedure();
return 0;
}