#include <bits/stdc++.h>
typedef long long ll;
#define M 1000000007
using namespace std;
void test_case() {
string s;
cin >> s;
// ahne?
int on = (int)s.length();
while(true) {
//cout << s << endl;
int n = (int)s.length();
char c = 'A';
int mxlen = -1;
int start = 0;
for (int i = 1; i < n; ++i) {
if (s[start] != s[i]) {
if (mxlen < i - start) {
c = s[start];
}
mxlen = max(mxlen, i - start);
start = i;
}
}
if (n - start > mxlen && mxlen != -1) {
c = s[n-1];
}
if (mxlen == -1) break;
//cout << mxlen << " " << c << " " << start << "\n";
// remove from start if possible
if (s[0] != c) {
string ns = "";
for (int i = 0; i < n; ++i) {
if (s[i+1] == c) {
i++;
continue;
}
ns += s[i];
}
s = ns;
} else {
string ns;
bool r = false;
for (int i = 1; i < n; ++i) {
if (s[i] != c && !r) {
r = true;
continue;
}
ns += s[i];
}
s = ns;
}
}
cout << on - (int)s.length();
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
test_case();
cout << "\n";
//cout << endl;
}
return 0;
}