#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

char str[100000];
int pre[100000], suc[100000], sum[100000];

int main() {
	int test;
	scanf("%d", &test);
	for (int cas = 1; cas <= test; ++cas) {
		scanf("%s", str + 1);
		int n = strlen(str + 1);
		for (int i = 1; i <= n; ++i)
			sum[i] = sum[i - 1] + str[i] - 'A';
		pre[1] = 1;
		for (int i = 2; i <= n; ++i)
			if (str[i] != 'A')
				pre[i] = i;
			else
				pre[i] = pre[i - 1];
		suc[n + 1] = n + 1;
		for (int i = n; i > 0; --i)
			if (str[i] != 'A')
				suc[i] = i;
			else
				suc[i] = suc[i + 1];
		int ans = 0x3f3f3f3f;
		for (int i = n; i > 0; --i) {
			int t = sum[pre[i]] + pre[i] - 1;
			if (suc[i + 1] != n + 1)
				t += pre[i] + n - suc[i + 1]
					+ sum[n] - sum[suc[i + 1] - 1];
			ans = min(ans, t);
		}
		printf("%d\n", ans);
	}
	return 0;
}