#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string shrink(const string &str)
{
    int len = str.size();
    if (len <= 1)
        return str;
    vector<char> v;
    for (int i = 0; i < len - 1; i++)
        if (str[i] == str[i + 1])
            while (i + 1 < len && str[i] == str[i + 1])
                i++;
        else
            v.push_back(str[i]);
    if (str[len - 2] != str[len - 1])
        v.push_back(str[len - 1]);
    return string(v.begin(), v.end());
}
int main()
{
    int n;
    string s;
    cin >> n;
    while (n--)
    {
        cin >> s;
        int mmax = s.size(), mmin = s.size();
        for (char ch = 'A'; ch <= 'C'; ch++)
            for (int i = 0; i < s.size(); ++i)
                for (int j = 0; j < 3; ++j)
                {
                    string str = s.substr(0, i + 1) + ch + s.substr(i + 1);
                    int len = str.size();
                    while (len > (str = shrink(str)).size())
                        len = str.size();
                    mmin = min(mmin, len);
                }
        cout << mmax - mmin + 1 << endl;
    }
    return 0;
}