#include<bits/stdc++.h>
using namespace std;

#define ll long long int
#define ull unsigned long long
#define pll pair<ll,ll>
#define MS(x, y) memset(x, y, sizeof(x))
#define all(x) x.begin(),x.end()
#define ff first
#define ss second
#define INFL LLONG_MAX
#define pb push_back
#define FIO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

const ll N = 1e5 + 5;
const ll M = 1e3;
const ll mod = 1e7 + 7;
const ll m1 = 1e9 + 7;
const ll m2 = 1e9 + 9;
const ll p1 = 402653189;
const ll p2 = 1610612741;
const int LN = 32;

ll powermodm(ll x,ll n,ll M){ll result=1;while(n>0){if(n % 2 ==1)result=(result * x)%M;x=(x*x)%M;n=n/2;}return result;}
ll power(ll _a,ll _b){ll _r=1;while(_b){if(_b%2==1)_r=(_r*_a);_b/=2;_a=(_a*_a);}return _r;}
ll gcd(ll a,ll b){if(a==0)return b;return gcd(b%a,a);}
ll lcm(ll a,ll b){return (max(a,b)/gcd(a,b))*min(a,b);}

ll dx[4]={-1,  1,  0,  0};
ll dy[4]={ 0,  0,  1, -1};

ll pw[LN],fact[N],invfact[N];

void pre()
{
    fact[0]=1;
    for(int i=0;i<LN;i++)pw[i]=power(2,i);
    for(int i=1;i<N;i++)fact[i]=(i*fact[i-1])%mod;
    for(int i=0;i<N;i++)invfact[i]=powermodm(fact[i],mod-2,mod);
}

int main()
{
    FIO;
    //pre();

    ll i,j;

    ll n;
    cin>>n;

    map <ll,ll> mp;
    ll a[n+1];
    for(i=1;i<=n;i++)
    {
        cin>>a[i];
        mp[a[i]]++;
    }
    ll ans = max(2LL,mp[0]);

    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n,i!=j;j++)
        {
            if(a[i]==0 && a[j]==0)continue;

            ll len = 2;
            ll t1 = a[i], t2 = a[j];
            mp[t1]--;
            mp[t2]--;

            vector <ll> tmp;
            tmp.pb(t1);
            tmp.pb(t2);

            while(mp.find(t1+t2)!=mp.end() && mp[t1+t2]>0)
            {
                len++;
                tmp.pb(t1+t2);
                mp[t1+t2]--;
                swap(t1,t2);
                t2 += t1;
            }
            ans = max(ans,len);
            for(ll k=0;k<tmp.size();k++)
                mp[tmp[k]]++;
        }
    }
    cout<<ans;

    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long int
#define ull unsigned long long
#define pll pair<ll,ll>
#define MS(x, y) memset(x, y, sizeof(x))
#define all(x) x.begin(),x.end()
#define ff first
#define ss second
#define INFL LLONG_MAX
#define pb push_back
#define FIO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

const ll N = 1e5 + 5;
const ll M = 1e3;
const ll mod = 1e7 + 7;
const ll m1 = 1e9 + 7;
const ll m2 = 1e9 + 9;
const ll p1 = 402653189;
const ll p2 = 1610612741;
const int LN = 32;

ll powermodm(ll x,ll n,ll M){ll result=1;while(n>0){if(n % 2 ==1)result=(result * x)%M;x=(x*x)%M;n=n/2;}return result;}
ll power(ll _a,ll _b){ll _r=1;while(_b){if(_b%2==1)_r=(_r*_a);_b/=2;_a=(_a*_a);}return _r;}
ll gcd(ll a,ll b){if(a==0)return b;return gcd(b%a,a);}
ll lcm(ll a,ll b){return (max(a,b)/gcd(a,b))*min(a,b);}

ll dx[4]={-1,  1,  0,  0};
ll dy[4]={ 0,  0,  1, -1};

ll pw[LN],fact[N],invfact[N];

void pre()
{
    fact[0]=1;
    for(int i=0;i<LN;i++)pw[i]=power(2,i);
    for(int i=1;i<N;i++)fact[i]=(i*fact[i-1])%mod;
    for(int i=0;i<N;i++)invfact[i]=powermodm(fact[i],mod-2,mod);
}

int main()
{
    FIO;
    //pre();

    ll i,j;

    ll n;
    cin>>n;

    multiset <ll> ms;
    ll a[n+1];

    for(i=1;i<=n;i++)
    {
        cin>>a[i];
        ms.insert(a[i]);
    }
    ll x = ms.count(0);
    ll ans = max(2LL,x);
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n,i!=j;j++)
        {
            if(a[i]==0 && a[j]==0)continue;
            ll len = 2;
            ll t1 = a[i], t2 = a[j];
            vector <ll> tmp;
            tmp.pb(t1);
            tmp.pb(t2);
            while(!ms.empty() && ms.find(t1+t2)!=ms.end())
            {
                len++;
                tmp.pb(t1+t2);
                ms.erase(t1+t2);
                swap(t1,t2);
                t2+=t1;
            }
            ans = max(ans,len);
            for(ll k=0;k<tmp.size();k++)
                ms.insert(tmp[k]);
        }
    }
    cout<<ans;

    return 0;
}


//satyaki3794
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <cassert>
#include <cstring>
#include <iomanip>
#define ff first
#define ss second
#define pb push_back
#define MOD (1000000007LL)
#define LEFT(n) (2*(n))
#define RIGHT(n) (2*(n)+1)

using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<int, ii> iii;

ll pwr(ll base, ll p, ll mod = MOD){
ll ans = 1;while(p){if(p&1)ans=(ans*base)%mod;base=(base*base)%mod;p/=2;}return ans;
}

int c0, n, arr[1004];
unordered_map<int, int> cnt, temp;

int main(){

    ios_base::sync_with_stdio(0);
    // freopen("input.txt", "r", stdin);

    cnt.reserve(1024);
    cnt.max_load_factor(0.25);

    temp.reserve(1024);
    temp.max_load_factor(0.25);

    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>arr[i];
        cnt[arr[i]]++;
        if(arr[i] == 0) c0++;
    }

    int ans = c0;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){

            if(i == j || (arr[i] == 0 && arr[j] == 0))  continue;

            temp = cnt;
            int len = 2;
            int a = arr[i], b = arr[j];
            temp[a]--;  temp[b]--;
            while(1){

                int next = a + b;
                if(temp.find(next) == temp.end() || temp[next] == 0) break;

                temp[next]--;
                len++;
                a = b;
                b = next;
            }

            ans = max(ans, len);
        }

    cout<<ans;
    return 0;
}


import sys, heapq as h
input = sys.stdin.readline

def getInts():
    return [int(s) for s in input().split()]

def getInt():
    return int(input())

def getStrs():
    return [s for s in input().split()]

def getStr():
    return input().strip()

def listStr():
    return list(input().strip())

import collections as col
import math

"""
Longest matching prefix and suffix
Then for each start / end point, the longest palindrome going forwards and then longest palidrome going backwards
"""

def longest_prefix_suffix_palindrome(S,N):
    i = -1
    while i+1 <= N-i-2 and S[i+1] == S[N-i-2]:
        i += 1
    return i

def longest_palindromic_prefix(S):
    tmp = S + "?"
    S = S[::-1]
    tmp = tmp + S
    N = len(tmp)
    lps = [0] * N
    for i in range(1, N):
        #Length of longest prefix till less than i
        L = lps[i - 1]
        # Calculate length for i+1
        while (L > 0 and tmp[L] != tmp[i]):
            L = lps[L - 1]

        #If character at current index and L are same then increment length by 1
        if (tmp[i] == tmp[L]):
            L += 1
        #Update the length at current index to L
        lps[i] = L

    return tmp[:lps[N - 1]]

def solve():
    S = getStr()
    N = len(S)
    i = longest_prefix_suffix_palindrome(S,N)
    #so S[:i+1] and S[N-i-1:] are palindromic
    if i >= N//2-1:
        return S
    #so there are least 2 elements between S[i] and S[N-i-1]
    new_str = S[i+1:N-i-1]
    longest_pref = longest_palindromic_prefix(new_str)
    longest_suff = longest_palindromic_prefix(new_str[::-1])[::-1]
    add_on = longest_pref if len(longest_pref) >= len(longest_suff) else longest_suff
    return S[:i+1] + add_on + S[N-i-1:]

for _ in range(getInt()):
    print(solve())
#print(solve())


t = int(input())

def findLongestPalindromicString(text, maxL):
    N = len(text)
    if N == 0:
        return ""
    N = 2*N+1    # Position count
    L = [0] * N
    L[0] = 0
    L[1] = 1
    C = 1     # centerPosition
    R = 2     # centerRightPosition
    i = 0    # currentRightPosition
    iMirror = 0     # currentLeftPosition
    maxLPSLength = 0
    maxLPSCenterPosition = 0
    start = -1
    end = -1
    diff = -1

    # Uncomment it to print LPS Length array
    # printf("%d %d ", L[0], L[1]);
    for i in range(2,N):

        # get currentLeftPosition iMirror for currentRightPosition i
        iMirror = 2*C-i
        L[i] = 0
        diff = R - i
        # If currentRightPosition i is within centerRightPosition R
        if diff > 0:
            L[i] = min(L[iMirror], diff)

        # Attempt to expand palindrome centered at currentRightPosition i
        # Here for odd positions, we compare characters and
        # if match then increment LPS Length by ONE
        # If even position, we just increment LPS by ONE without
        # any character comparison
        try:
            while ((i + L[i]) < N and (i - L[i]) > 0) and (((i + L[i] + 1) % 2 == 0) or (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
                L[i]+=1
        except Exception :
            pass

        if L[i] > maxLPSLength:        # Track maxLPSLength
            maxLPSLength = L[i]
            maxLPSCenterPosition = i

        # If palindrome centered at currentRightPosition i
        # expand beyond centerRightPosition R,
        # adjust centerPosition C based on expanded palindrome.
        if i + L[i] > R:
            C = i
            R = i + L[i]

    # Uncomment it to print LPS Length array
    # printf("%d ", L[i]);

    # print (L)
    # print(maxLPSCenterPosition, maxLPSLength)
    # print ("LPS of string is " + text + " : ")

    start_Max = 0
    end_Max = 0

    i = 1
    while (i <= maxL):
        if (L[i] == i):
            start_Max = i

        if (L[N-1-i] == i):
            end_Max = i

        i += 1

    if (start_Max > end_Max):
        return start_Max
    else :
        return -end_Max

# yo
for _ in range(t):

    s = input()

    n = len(s)

    prefix = ""
    suffix = ""
    remaining = s

    ans = 0
    for i in range (n//2):
        if (s[i] == s[n-1-i]):
            ans = i + 1

        else:
            break

    if (ans != 0):
        prefix = s[0:ans]
        suffix = s[n-ans:n]
        remaining = s[ans:n-ans]

    x = findLongestPalindromicString(remaining, n - 2*ans)

    temp = ""
    if (x < 0):
        temp = remaining[x:]
    else :
        temp = remaining[:x]

    print(prefix + temp + suffix)


t = int(input())

def findLongestPalindromicString(text, maxL):
    N = len(text)
    if N == 0:
        return 0
    N = 2*N+1    # Position count
    L = [0] * N
    L[0] = 0
    L[1] = 1
    C = 1     # centerPosition
    R = 2     # centerRightPosition
    i = 0    # currentRightPosition
    iMirror = 0     # currentLeftPosition
    maxLPSLength = 0
    maxLPSCenterPosition = 0
    start = -1
    end = -1
    diff = -1

    # Uncomment it to print LPS Length array
    # printf("%d %d ", L[0], L[1]);
    for i in range(2,N):

        # get currentLeftPosition iMirror for currentRightPosition i
        iMirror = 2*C-i
        L[i] = 0
        diff = R - i
        # If currentRightPosition i is within centerRightPosition R
        if diff > 0:
            L[i] = min(L[iMirror], diff)

        # Attempt to expand palindrome centered at currentRightPosition i
        # Here for odd positions, we compare characters and
        # if match then increment LPS Length by ONE
        # If even position, we just increment LPS by ONE without
        # any character comparison
        try:
            while ((i + L[i]) < N and (i - L[i]) > 0) and (((i + L[i] + 1) % 2 == 0) or (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
                L[i]+=1
        except Exception :
            pass

        if L[i] > maxLPSLength:        # Track maxLPSLength
            maxLPSLength = L[i]
            maxLPSCenterPosition = i

        # If palindrome centered at currentRightPosition i
        # expand beyond centerRightPosition R,
        # adjust centerPosition C based on expanded palindrome.
        if i + L[i] > R:
            C = i
            R = i + L[i]

    # Uncomment it to print LPS Length array
    # printf("%d ", L[i]);

    # print (L)
    # print(maxLPSCenterPosition, maxLPSLength)
    # print ("LPS of string is " + text + " : ")

    start_Max = 0
    end_Max = 0

    i = 1
    while (i <= maxL):
        if (L[i] == i):
            start_Max = i

        if (L[N-1-i] == i):
            end_Max = i

        i += 1

    if (start_Max > end_Max):
        return start_Max
    else :
        return -end_Max

# yo
for _ in range(t):

    s = input()

    n = len(s)

    prefix = ""
    suffix = ""
    remaining = s

    ans = 0
    for i in range (n//2):
        if (s[i] == s[n-1-i]):
            ans = i + 1

        else:
            break

    if (ans != 0):
        prefix = s[0:ans]
        suffix = s[n-ans:n]
        remaining = s[ans:n-ans]

    x = findLongestPalindromicString(remaining, n - 2*ans)

    temp = ""
    if (x == 0):
        pass
    elif (x < 0):
        temp = remaining[x:]
    else :
        temp = remaining[:x]

    print(prefix + temp + suffix)


t = int(input())

def findLongestPalindromicString(text, maxL):
    N = len(text)
    if N == 0:
        return ""
    N = 2*N+1    # Position count
    L = [0] * N
    L[0] = 0
    L[1] = 1
    C = 1     # centerPosition
    R = 2     # centerRightPosition
    i = 0    # currentRightPosition
    iMirror = 0     # currentLeftPosition
    maxLPSLength = 0
    maxLPSCenterPosition = 0
    start = -1
    end = -1
    diff = -1

    # Uncomment it to print LPS Length array
    # printf("%d %d ", L[0], L[1]);
    for i in range(2,N):

        # get currentLeftPosition iMirror for currentRightPosition i
        iMirror = 2*C-i
        L[i] = 0
        diff = R - i
        # If currentRightPosition i is within centerRightPosition R
        if diff > 0:
            L[i] = min(L[iMirror], diff)

        # Attempt to expand palindrome centered at currentRightPosition i
        # Here for odd positions, we compare characters and
        # if match then increment LPS Length by ONE
        # If even position, we just increment LPS by ONE without
        # any character comparison
        try:
            while ((i + L[i]) < N and (i - L[i]) > 0) and (((i + L[i] + 1) % 2 == 0) or (text[(i + L[i] + 1) // 2] == text[(i - L[i] - 1) // 2])):
                L[i]+=1
        except Exception :
            pass

        if L[i] > maxLPSLength:        # Track maxLPSLength
            maxLPSLength = L[i]
            maxLPSCenterPosition = i

        # If palindrome centered at currentRightPosition i
        # expand beyond centerRightPosition R,
        # adjust centerPosition C based on expanded palindrome.
        if i + L[i] > R:
            C = i
            R = i + L[i]

    # Uncomment it to print LPS Length array
    # printf("%d ", L[i]);

    # print (L)
    # print(maxLPSCenterPosition, maxLPSLength)
    # print ("LPS of string is " + text + " : ")

    start_Max = 0
    end_Max = 0

    i = 1
    while (i <= maxL):
        if (L[i] == i):
            start_Max = i

        if (L[N-1-i] == i):
            end_Max = i

        i += 1

    if (start_Max > end_Max):
        return start_Max
    else :
        return -end_Max

for _ in range(t):

    s = input()

    n = len(s)

    prefix = ""
    suffix = ""
    remaining = s

    ans = 0
    for i in range (n//2):
        if (s[i] == s[n-1-i]):
            ans = i + 1

        else:
            break

    if (ans != 0):
        prefix = s[0:ans]
        suffix = s[n-ans:n]
        remaining = s[ans:n-ans]

    x = findLongestPalindromicString(remaining, n - 2*ans)

    temp = ""
    if (x < 0):
        temp = remaining[x:]
    else :
        temp = remaining[:x]

    print(prefix + temp + suffix)


class SegmentTree:
    def __init__(self, data, default=0, func=lambda a,b:a+b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

def pre(s):
    n = len(s)
    pi=[0]*n
    for i in range(1,n):
        j = pi[i-1]
        while j and s[i] != s[j]:
            j = pi[j-1]
        if s[i] == s[j]:
            j += 1
        pi[i] = j
    return pi

for _ in range(int(input())):
    i = 0
    s=input()
    j = len(s)-1
    while i < j:
        if s[i] == s[j]:
            i += 1
            j -= 1
        else:break
    ans = ['','','']
    ans[0] = s[:i]
    ans[2] = ans[0][::-1]
    s = s[i:j+1]

    st = s + s[::-1]
    mx = pre(st)[-1]
    ans[1] = s[:mx]
    #print(ans)
    s = s[::-1]
    st = s + s[::-1]
    mx = pre(st)[-1]
    if mx > len(ans[1]):
        ans[1] = s[:mx]
    print("".join(ans))


# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

for _ in range(int(input())):
    s = input()
    n = len(s)
    pre = ['']*n
    pree = ['']*n
    suf = ['']*n
    suff = ['']*n
    pre[0] = s[0]
    pree[0] = s[0]
    suf[0] = s[-1]
    suff[0] = s[-1]
    ans = 1
    anstr = s[0]
    if s[0] == s[-1] and n != 1:
        ans = 2
        anstr = 2*s[0]
    for i in range(1, n):
        pre[i] = pre[i-1] + s[i]
        pree[i] = s[i] + pree[i-1]
        suf[i] = s[-1-i] + suf[i-1]
        suff[i] = suff[i-1] + s[-1-i]
        if pre[i] == pree[i]:
            ans = i+1
            anstr = pre[i]
        if suf[i] == suff[i]:
            ans = i+1
            anstr = suf[i]

    for i in range(1, n//2+1):
        curpre = pre[i]
        cursuf = suf[i]

        j=i+1
        if curpre == suff[i]:
            ans = 2*(i+1)
            anstr = curpre + suf[i]

        count = 1
        toadd = ""
        rx = 0
        while j < n and i-count >= 0:
            if s[j] == s[i-count]:
                count += 1
                rx += 1
                toadd += s[j]
                j += 1
            else:break

        remainder = i - rx - 1
        if pre[remainder] == suff[remainder]:
            ans = 2*i + 1
            anstr = curpre + toadd + suf[remainder]

    largest = -1
    for i in range(n):
        if pre[i] == suff[i]:
            largest = i
    if largest >= 0:
        endex = n - 2 - largest
        two=False
        ax = largest
        while endex >= 0:
            if endex != 0 and s[endex] == s[endex-1]:
                ax += 2
                endex -= 2
                two = True
            elif not two:
                ax += 1
                break
            else:break

        newans = pre[largest]+suf[ax]
        if n >= len(newans) > ans:
            anstr = newans

    print(anstr)


class SegmentTree:
    def __init__(self, data, default=0, func=lambda a,b:a+b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

def pre(s):
    n = len(s)
    pi=[0]*n
    for i in range(1,n):
        j = pi[i-1]
        while j and s[i] != s[j]:
            j = pi[j-1]
        if s[i] == s[j]:
            j += 1
        pi[i] = j
    return pi

for _ in range(int(input())):
    i = 0
    s=input()
    j = len(s)-1
    while i < j:
        if s[i] == s[j]:
            i += 1
            j -= 1
        else:break
    ans = ['','','']
    ans[0] = s[:i]
    ans[2] = ans[0][::-1]
    s = s[i:j+1]
    if not len(s):
        print("".join(ans))
        continue
    st = s + s[::-1]
    mx = pre(st)[-1]
    ans[1] = s[:mx]
    #print(ans)
    s = s[::-1]
    st = s + s[::-1]
    mx = pre(st)[-1]
    if mx > len(ans[1]):
        ans[1] = s[:mx]
    print("".join(ans))


class SegmentTree:
    def __init__(self, data, default=0, func=lambda a,b:a+b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# ------------------- fast io --------------------

def pre(s):
    n = len(s)
    pi=[0]*n
    for i in range(1,n):
        j = pi[i-1]
        while j and s[i] != s[j]:
            j = pi[j-1]
        if s[i] == s[j]:
            j += 1
        pi[i] = j
    return pi

for _ in range(int(input())):
    i = 0
    s=input()
    j = len(s)-1
    while i < j:
        if s[i] == s[j]:
            i += 1
            j -= 1
        else:break
    ans = ['','','']
    ans[0] = s[:i]
    ans[2] = ans[0][::-1]
    s = s[i:j+1]
    #print(ans, s)
    if not len(s):
        print("".join(ans))
        continue
    st = s + "#" + s[::-1]
    #print(st, pre(st))
    mx = pre(st)[-1]
    ans[1] = s[:mx]
    #print(ans)
    s = s[::-1]
    st = s + "#" + s[::-1]
    #print(st, pre(st))
    mx = pre(st)[-1]
    if mx > len(ans[1]):
        ans[1] = s[:mx]
    print("".join(ans))


t = int(input())

for i in range(t):
    s = list(input())
    prefix = []
    middleFromStart = []
    middleFromEnd = []
    endIndex = 0
    if len(s) == 1:
        print(s[0])
    else:
        for j in range(len(s)):
            if s[j] == s[-1 - endIndex]:
                prefix.append(s[j])
                s[j] = 1
                s[-1 - endIndex] = 1
                endIndex += 1
            else:
                break
        middle = [x for x in s if x != 1]
        middleReversed = middle[::-1]
        bestMid = ""
        for j in range(len(middle), -1, -1):
            if middle[:j] == list(reversed(middle[:j])) and len(middle[:j]) > len(bestMid):
                bestMid = middle[:j]
                break
        for j in range(len(middleReversed), -1, -1):
            if middleReversed[:j] == list(reversed(middleReversed[:j])) and len(middleReversed[:j]) > len(bestMid):
                bestMid = middleReversed[:j]
                break
        print(''.join(prefix) + ''.join(bestMid) + ''.join(prefix[::-1]))


t = int(input())

for i in range(t):
    s = list(input())
    prefix = []
    endIndex = 0
    if len(s) == 1:
        print(s[0])
    else:
        for j in range(len(s)//2):
            if s[j] == s[-1 - endIndex]:
                prefix.append(s[j])
                s[j] = 1
                s[-1 - endIndex] = 1
                endIndex += 1
            else:
                break
        middle = [x for x in s if x != 1]
        middleReversed = middle[::-1]
        bestMid = ""
        for j in range(len(middle), -1, -1):
            if middle[:j] == list(reversed(middle[:j])) and len(middle[:j]) > len(bestMid):
                bestMid = middle[:j]
                break
        for j in range(len(middleReversed), -1, -1):
            if middleReversed[:j] == list(reversed(middleReversed[:j])) and len(middleReversed[:j]) > len(bestMid):
                bestMid = middleReversed[:j]
                break
        print(''.join(prefix) + ''.join(bestMid) + ''.join(prefix[::-1]))


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)

	if n == 1:
		print(s)
	else:
		l, r = 0, n-1
		while l < r and s[l] == s[r]:
			l += 1
			r -= 1

		# print("l:", l)
		# print("r:", r)

		added = 0
		center_piece = []

		# need to find palindrome from l to r inclisif
		for center in range(l, r):
			offset = 1
			while center-offset >= l and center + offset <= r and s[center-offset] == s[center+offset]:
				offset += 1

			if center-offset < l or center+offset> r:
				if 2*(offset-1)+1 >= added:
					added = 2*(offset-1)+1
					center_piece = [center-offset+1, center+offset-1]

		for center1 in range(l, r):
			center2 = center1 + 1
			if s[center1] == s[center2]:
				# print("center1", center1)
				# print("center2", center2)
				offset = 1
				while center1-offset >= l and center2 + offset <= r and s[center1-offset] == s[center2+offset]:
					offset += 1

				if center1-offset < l or center2+offset> r:
					if 2*(offset-1)+2 >= added:
						added = 2*(offset-1)+2
						center_piece = [center1-offset+1, center2+offset-1]

		print(s[:l] + s[center_piece[0]: center_piece[1]+1] + s[r+1:])


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)

	if n == 1:
		print(s)
	else:
		l, r = 0, n-1
		while l+1 < r-1 and s[l] == s[r]:
			l += 1
			r -= 1

		# print("l:", l)
		# print("r:", r)

		added = 0
		center_piece = []

		# need to find palindrome from l to r inclisif
		for center in range(l, r):
			offset = 1
			while center-offset >= l and center + offset <= r and s[center-offset] == s[center+offset]:
				offset += 1

			if center-offset < l or center+offset> r:
				if 2*(offset-1)+1 >= added:
					added = 2*(offset-1)+1
					center_piece = [center-offset+1, center+offset-1]

		for center1 in range(l, r):
			center2 = center1 + 1
			if center2 < n and s[center1] == s[center2]:
				# print("center1", center1)
				# print("center2", center2)
				offset = 1
				while center1-offset >= l and center2 + offset <= r and s[center1-offset] == s[center2+offset]:
					offset += 1

				if center1-offset < l or center2+offset> r:
					if 2*(offset-1)+2 >= added:
						added = 2*(offset-1)+2
						center_piece = [center1-offset+1, center2+offset-1]

		print(s[:l] + s[center_piece[0]: center_piece[1]+1] + s[r+1:])


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)

	if n == 1:
		print(s)
	else:
		l, r = 0, n-1
		while l < r and s[l] == s[r]:
			l += 1
			r -= 1

		# print("l:", l)
		# print("r:", r)

		added = 0
		center_piece = []

		# need to find palindrome from l to r inclisif
		for center in range(l, r):
			offset = 1
			while center-offset >= l and center + offset <= r and s[center-offset] == s[center+offset]:
				offset += 1

			if center-offset < l or center+offset> r:
				if 2*(offset-1)+1 >= added:
					added = 2*(offset-1)+1
					center_piece = [center-offset+1, center+offset-1]

		for center1 in range(l, r):
			center2 = center1 + 1
			if center2 < n and s[center1] == s[center2]:
				# print("center1", center1)
				# print("center2", center2)
				offset = 1
				while center1-offset >= l and center2 + offset <= r and s[center1-offset] == s[center2+offset]:
					offset += 1

				if center1-offset < l or center2+offset> r:
					if 2*(offset-1)+2 >= added:
						added = 2*(offset-1)+2
						center_piece = [center1-offset+1, center2+offset-1]

		print(s[:l] + s[center_piece[0]: center_piece[1]+1] + s[r+1:])


# Legends Always Come Up with Solution
# Author: Manvir Singh

import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict,deque,Counter
from bisect import *
from math import sqrt,pi
import math
from itertools import permutations
from copy import deepcopy
def main():
    for t in range(int(input())):
        s=input().rstrip()
        n=len(s)
        i=0
        j=n-1
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
        if i==j-1:
            print(s)
            continue
        x=i
        y=j
        m=y-x+1
        pl=0
        for k in range(m,0,-1):
            i=x
            j=x+k-1
            while i<j and s[i]==s[j]:
                i+=1
                j-=1
            if (j+1==i and k%2==0) or (i==j and k%2):
                pl=k
                break
        sl=0
        for k in range(x,y+1):
            i=k
            j=y
            while i<j and s[i]==s[j]:
                i+=1
                j-=1
            if (j+1==i and (y-k+1)%2==0) or (i==j and (y-k+1)%2):
                sl=y-k+1
                break
        if pl>sl:
            print(s[:x+pl]+s[y+1:])
        else:
            print(s[:x]+s[y-sl+1:])

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


# Legends Always Come Up with Solution
# Author: Manvir Singh

import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict,deque,Counter
from bisect import *
from math import sqrt,pi
import math
from itertools import permutations
from copy import deepcopy
def main():
    for t in range(int(input())):
        s=input().rstrip()
        if s==s[::-1]:
            print(s)
            continue
        n=len(s)
        i=0
        j=n-1
        while i<j and s[i]==s[j]:
            i+=1
            j-=1
        x=i
        y=j
        m=y-x+1
        pl=0
        for k in range(m,0,-1):
            i=x
            j=x+k-1
            while i<j and s[i]==s[j]:
                i+=1
                j-=1
            if (j+1==i and k%2==0) or (i==j and k%2):
                pl=k
                break
        sl=0
        for k in range(x,y+1):
            i=k
            j=y
            while i<j and s[i]==s[j]:
                i+=1
                j-=1
            if (j+1==i and (y-k+1)%2==0) or (i==j and (y-k+1)%2):
                sl=y-k+1
                break
        if pl>sl:
            print(s[:x+pl]+s[y+1:])
        else:
            print(s[:x]+s[y-sl+1:])

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

if __name__ == "__main__":
    main()


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
# from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#sys.setrecursionlimit(1000000)
mod = 998244353

def pallin(x):
    n=len(x)
    for i in range(len(x)):
        if x[i]!=x[n-i-1]:
            return False
    return True

for t in range(int(data())):
    s=data()
    l=s[0]
    n=len(s)
    for i in range(n):
        if pallin(s[:n-i]):
            l=s[:n-i]
            break
    for i in range(1,n):
        if pallin(s[i:]):
            if len(s[i:])>len(l):
                l=s[i:]
            break
    for j in range(n//2):
        if s[j]==s[n-j-1]:
            for i in range(j+1,n-j-1):
                if pallin(s[j+1:n-i-j-1]):
                    k=s[0:j+1]+s[j+1:n-i-j-1]+s[n-j-1:]
                    if len(l)<len(k):
                        l=k
                    break
            for i in range(j+1,n-j-1):
                if pallin(s[i:n-j-1]):
                    k=s[0:j+1]+s[i:n-j-1]+s[n-j-1:]
                    if len(k)>len(l):
                        l=k
                    break
        else:
            break
    print(l)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
# from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#sys.setrecursionlimit(1000000)
mod = 998244353

def pallin(x):
    n=len(x)
    for i in range(len(x)):
        if x[i]!=x[n-i-1]:
            return False
    return True

for t in range(int(data())):
    s=data()
    l=s[0]
    n=len(s)
    for i in range(n):
        k=s[:n-i]
        if pallin(k):
            l=k
            break
    for i in range(1,n):
        k=s[i:]
        if pallin(k):
            if len(k)>len(l):
                l=k
            break
    for j in range(n//2):
        if s[j]==s[n-j-1]:
            for i in range(j+1,n-j-1):
                if pallin(s[j+1:i+1]):
                    k=s[0:j+1]+s[j+1:i+1]+s[n-j-1:]
                    if len(l)<len(k):
                        l=k
            for i in range(j+1,n-j-1):
                if pallin(s[i:n-j-1]):
                    k=s[0:j+1]+s[i:n-j-1]+s[n-j-1:]
                    if len(k)>len(l):
                        l=k
                    break
        else:
            break
    print(l)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
# from math import *
from collections import defaultdict as dd, deque
def data(): return sys.stdin.readline().strip()
def mdata(): return map(int, data().split())
#sys.setrecursionlimit(1000000)
mod = 998244353

def pallin(x):
    n=len(x)
    for i in range(len(x)):
        if x[i]!=x[n-i-1]:
            return False
    return True

for t in range(int(data())):
    s=data()
    l=s[0]
    n=len(s)
    for i in range(n):
        k=s[:n-i]
        if pallin(k):
            l=k
            break
    for i in range(1,n):
        k=s[i:]
        if pallin(k):
            if len(k)>len(l):
                l=k
            break
    for j in range(n//2):
        if s[j]!=s[n-j-1]:
            if j>0:
                j-=1
                for i in range(j+1,n-j-1):
                    if pallin(s[j+1:i+1]):
                        k=s[0:j+1]+s[j+1:i+1]+s[n-j-1:]
                        if len(l)<len(k):
                            l=k
                for i in range(j+1,n-j-1):
                    if pallin(s[i:n-j-1]):
                        k=s[0:j+1]+s[i:n-j-1]+s[n-j-1:]
                        if len(k)>len(l):
                            l=k
                        break
            break
    print(l)


def longpal(s):
    l = len(s)
    ml = 1
    for i in range(1,l):
        s1 = s[:i]
        f = 0
        for j in range(i//2):
            if s1[j]!=s1[i-j-1]:
                f = 1
                break
        if f==0:
            ml = max(ml,i)
    return ml,s[:ml]
# 1
# mmwbbbwmmmgyniywe
cases = int(input())
for t in range(cases):
    s = input()
    l = len(s)
    if l == 1:
        print(s)
    else:
        i = 0
        j = l - 1
        prefix = ''
        while i < j:
            if s[i] == s[j]:
                prefix += s[i]
                i += 1
                j -= 1
            else:
                break
        if i <= j:
            # right palindrome
            l1, s1 = longpal(s[i:j + 1][::-1])
            # left palindrome
            l2, s2 = longpal(s[i:j + 1])
            if l1 >= l2:
                print(prefix + s1 + prefix[::-1])
            else:
                print(prefix + s2 + prefix[::-1])
        else:
            print(prefix + prefix[::-1])

    # print("====")


def longpal(s):
    fr = s.rfind(s[0])
    sp = 0
    f = 0
    end = fr
    while fr>=sp:
        if s[sp]==s[fr]:
            if f==0:
                end = fr
                f=1
            sp+=1
        else:
            f = 0
            sp=0
            if s[sp]==s[fr]:
                end = fr
                sp+=1
                f=1
        fr-=1
    l = end + 1
    s = s[:l]
    return l,s

cases = int(input())
out = ''
for t in range(cases):
    s = input()
    if t==427:
        print(s)
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    if i<=j:
        # right palindrome
        l1,s1 = longpal(s[i:j+1][::-1])
        # left palindrome
        l2,s2 = longpal(s[i:j+1])
        if l1>=l2:
            out += prefix+s1+prefix[::-1] +'\n'
        else:
            out += prefix+s2+prefix[::-1] +'\n'
    else:
        out += prefix+prefix[::-1]
print(out)


def longpal(s):
    fr = s.rfind(s[0])
    sp = 0
    f = 0
    end = fr
    while fr>=sp:
        if s[sp]==s[fr]:
            if f==0:
                end = fr
                f=1
            sp+=1
        else:
            f = 0
            sp=0
            if s[sp]==s[fr]:
                end = fr
                sp+=1
                f=1
        fr-=1
    l = end + 1
    s = s[:l]
    return l,s

cases = int(input())
out = ''
for t in range(cases):
    s = input()
    if cases == 500 and t==427:
        print(s)
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    if i<=j:
        # right palindrome
        l1,s1 = longpal(s[i:j+1][::-1])
        # left palindrome
        l2,s2 = longpal(s[i:j+1])
        if l1>=l2:
            out += prefix+s1+prefix[::-1] +'\n'
        else:
            out += prefix+s2+prefix[::-1] +'\n'
    else:
        out += prefix+prefix[::-1] + '\n'
print(out)


cases = int(input())
for t in range(cases):
    s = input()
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    start = i
    end = j
    # right palindrome
    sp = start
    ep = end
    i = sp
    f = 0
    while i<=ep:
        if s[i]==s[ep]:
            if f==0:
                sp = i
                f = 1
            ep-=1
        else:
            ep = end
            sp = i
            if f==1:
                i-=1
            f = 0
        i+=1
    l1 = end-sp+1
    s1 = s[sp:end+1]

    # left palindrome
    sp = start
    ep = end
    i = ep
    f = 0
    while i>=sp:
        if s[i]==s[sp]:
            if f==0:
                ep=i
                f=1
            sp+=1
        else:
            sp = start
            ep = i
            if f==1:
                i+=1
            f = 0
        i-=1
    l2 = ep-start+1
    s2 = s[start:ep+1]

    # print(prefix)
    # print(l1,s1)
    # print(l2,s2)

    if l1>=l2:
        print(prefix+s1+prefix[::-1])
    else:
        print(prefix+s2+prefix[::-1])

    # print("====")


def longpal(s):
    fr = s.rfind(s[0])
    sp = 0
    f = 0
    end = fr
    while fr>=sp:
        if s[sp]==s[fr]:
            if f==0:
                end = fr
                f=1
            sp+=1
        else:
            f = 0
            sp=0
            if s[sp]==s[fr]:
                end = fr
                sp+=1
                f=1
        fr-=1
    l = end + 1
    s = s[:l]
    return l,s

cases = int(input())
for t in range(cases):
    s = input()
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    if i<=j:
        # right palindrome
        l1,s1 = longpal(s[i:j+1][::-1])
        # left palindrome
        l2,s2 = longpal(s[i:j+1])
        if l1>=l2:
            print(prefix+s1+prefix[::-1])
        else:
            print(prefix+s2+prefix[::-1])
    else:
        print(prefix+prefix[::-1])

    # print("====")


def longpal(s):
    l = len(s)
    ml = 0
    for i in range(1,l):
        s1 = s[:i]
        f = 0
        for j in range(i//2):
            if s[j]!=s[i-j-1]:
                f = 1
                break
        if f==0:
            ml = max(ml,i)
    return ml,s[:ml]
# 1
# mmwbbbwmmmgyniywe
cases = int(input())
for t in range(cases):
    s = input()
    l = len(s)
    if l == 1:
        print(s)
    else:
        i = 0
        j = l - 1
        prefix = ''
        while i < j:
            if s[i] == s[j]:
                prefix += s[i]
                i += 1
                j -= 1
            else:
                break
        if i <= j:
            # right palindrome
            l1, s1 = longpal(s[i:j + 1][::-1])
            # left palindrome
            l2, s2 = longpal(s[i:j + 1])
            if l1 >= l2:
                print(prefix + s1 + prefix[::-1])
            else:
                print(prefix + s2 + prefix[::-1])
        else:
            print(prefix + prefix[::-1])

    # print("====")


def longpal(s):
    fr = s.rfind(s[0])
    sp = 0
    f = 0
    end = fr
    while fr>=sp:
        if s[sp]==s[fr]:
            if f==0:
                end = fr
                f=1
            sp+=1
        else:
            f = 0
            sp=0
            if s[sp]==s[fr]:
                end = fr
                sp+=1
                f=1
        fr-=1
    l = end + 1
    s = s[:l]
    return l,s

cases = int(input())
out = ''
for t in range(cases):
    s = input()
    if cases == 500 and t==427:
        print(s)
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    if i<=j:
        # right palindrome
        l1,s1 = longpal(s[i:j+1][::-1])
        # left palindrome
        l2,s2 = longpal(s[i:j+1])
        if l1>=l2:
            out += prefix+s1+prefix[::-1] +'\n'
        else:
            out += prefix+s2+prefix[::-1] +'\n'
    else:
        out += prefix+prefix[::-1]
print(out)


def longpal(s):
    fr = s.rfind(s[0])
    sp = 0
    f = 0
    end = fr
    while fr>=sp:
        if s[sp]==s[fr]:
            if f==0:
                end = fr
                f=1
            sp+=1
        else:
            f = 0
            sp=0
            if s[sp]==s[fr]:
                end = fr
                sp+=1
                f=1
        fr-=1
    l = end + 1
    s = s[:l]
    return l,s

cases = int(input())
for t in range(cases):
    s = input()
    l = len(s)
    i = 0
    j = l-1
    prefix = ''
    while i<j:
        if s[i]==s[j]:
            prefix+=s[i]
            i+=1
            j-=1
        else:
            break
    start = i
    end = j
    # right palindrome
    l1,s1 = longpal(s[i:j+1][::-1])
    # left palindrome
    l2,s2 = longpal(s[i:j+1])

    # print(prefix)
    # print(l1,s1)
    # print(l2,s2)

    if l1>=l2:
        print(prefix+s1+prefix[::-1])
    else:
        print(prefix+s2+prefix[::-1])

    # print("====")


#from sys import stdin
#inf=stdin
#inf=open("data1.txt",'rt')

#n,k=map(int,inf.readline().split(" "))
#arr=list(map(int,inf.readline().split(" ")))

# Python program to implement Manacher's Algorithm

# def findLongestPalindromicString(text):
# 	N = len(text)
# 	if N == 0:
# 		return ""
# 	elif N==1:
# 		return text
# 	N = 2*N+1 # Position count
# 	L = [0] * (N+1)
# 	L[0] = 0
# 	L[1] = 1
# 	C = 1	 # centerPosition
# 	R = 2	 # centerRightPosition
# 	i = 0 # currentRightPosition
# 	iMirror = 0	 # currentLeftPosition
# 	maxLPSLength = 0
# 	maxLPSCenterPosition = 0
# 	start = -1
# 	end = -1
# 	diff = -1
# 	for i in range(2,N):
# 		iMirror = 2*C-i
# 		L[i] = 0
# 		diff = R - i
# 		if diff > 0:
# 			L[i] = min(L[iMirror], diff)

# 		while (((i + L[i]) + 1 < N and (i - L[i]) > 0) and (((i + L[i] + 1) % 2 == 0) or (text[((i + L[i] + 1) // 2)] == text[((i - L[i] - 1) // 2)]))):
# 			L[i]+=1

# 		if L[i] > maxLPSLength:	 # Track maxLPSLength
# 			maxLPSLength = L[i]
# 			maxLPSCenterPosition = i

# 		if i + L[i] > R:
# 			C = i
# 			R = i + L[i]

# 	start = (maxLPSCenterPosition - maxLPSLength) // 2
# 	end = start + maxLPSLength - 1

# 	if(start!=0):
# 		findLongestPalindromicString(text[:end])
# 	else:
# 		return text[:end+1]

for qw in range(int(input())):
	s=input()
	n=len(s)
	if(n==1):
		print(s)
		continue
	else:
		i=0
		j=n-1
		count=0
		while j>i:
			if(s[i]==s[j]):
				count+=1
				i+=1
				j-=1
			else:
				break
		suffix=s[:i]
		prefix=s[j+1:]
		middle=s[i:j+1]

		if(len(middle)>0):
			end=len(middle)
			while True:
				if(middle[:end]==middle[:end][::-1]):
					break
				end-=1

			middle1=middle[::-1]
			ende=len(middle1)
			while True:
				if(middle1[:ende]==middle1[:ende][::-1]):
					break
				ende-=1
			if(ende>end):
				print(suffix+middle1[:ende]+prefix)
			else:
				print(suffix+middle[:end]+prefix)
		else:
			print(suffix+prefix)

# for i in dicti:
# 	temp=0
# 	for j in helper:
# 		if(j[0]<=i[0] and j[1]<=i[1]):
# 			temp+=(i[0]-j[0]+1)*(i[1]-j[1]+1)
# 		if(j[1]<=i[0] and j[0]<=i[1] and j[0]!=j[1]):
# 			temp+=(i[0]-j[1]+1)*(i[1]-j[0]+1)
# 	count+=temp*dicti[i]

# def all_partitions(string):
#     for cutpoints in range(1 << (len(string)-1)):
#         result = []
#         lastcut = 0
#         for i in range(len(string)-1):
#             if (1<<i) & cutpoints != 0:
#                 result.append(string[lastcut:(i+1)])
#                 lastcut = i+1
#         result.append(string[lastcut:])
#         yield result

# maxyet=0
# store={'h': -6, 'e': -7, 'l': -8, 'o': 3, 'he': 3, 'hel': -3, 'el': 0, 'hell': 6, 'ell': -5, 'll': 10, 'hello': -3, 'ello': -8, 'llo': 9, 'lo': -6}

# def quality(stri):
# 	return store[stri]

# for partition in all_partitions("hel"):
#     temp=0
#     for i in partition:
#     	temp+=quality(i)
#     if(temp>maxyet):
#     	print(partition)
#     	maxyet=temp

# print(maxyet)


#from sys import stdin
#inf=stdin
#inf=open("data1.txt",'rt')

#n,k=map(int,inf.readline().split(" "))
#arr=list(map(int,inf.readline().split(" ")))

# Python program to implement Manacher's Algorithm

def findLongestPalindromicString(text):
	N = len(text)
	if N == 0:
		return ""
	elif N==1:
		return text
	N = 2*N+1 # Position count
	L = [0] * (N+1)
	L[0] = 0
	L[1] = 1
	C = 1	 # centerPosition
	R = 2	 # centerRightPosition
	i = 0 # currentRightPosition
	iMirror = 0	 # currentLeftPosition
	maxLPSLength = 0
	maxLPSCenterPosition = 0
	start = -1
	end = -1
	diff = -1
	for i in range(2,N):
		iMirror = 2*C-i
		L[i] = 0
		diff = R - i
		if diff > 0:
			L[i] = min(L[iMirror], diff)

		while (((i + L[i]) + 1 < N and (i - L[i]) > 0) and (((i + L[i] + 1) % 2 == 0) or (text[((i + L[i] + 1) // 2)] == text[((i - L[i] - 1) // 2)]))):
			L[i]+=1

		if L[i] > maxLPSLength:	 # Track maxLPSLength
			maxLPSLength = L[i]
			maxLPSCenterPosition = i

		if i + L[i] > R:
			C = i
			R = i + L[i]

	start = (maxLPSCenterPosition - maxLPSLength) // 2
	end = start + maxLPSLength - 1

	if(start!=0):
		findLongestPalindromicString(text[:end])
	else:
		return text[:end+1]

for qw in range(int(input())):
	s=input()
	n=len(s)
	if(n==1):
		print(s)
		continue
	else:
		i=0
		j=n-1
		count=0
		while j>i:
			if(s[i]==s[j]):
				count+=1
				i+=1
				j-=1
			else:
				break
		suffix=s[:i]
		prefix=s[j+1:]
		middle=s[i:j+1]

		if(len(middle)>0):
			n1=findLongestPalindromicString(middle[:])
			n2=findLongestPalindromicString(middle[::-1])
			if(n1==None):
				n1=middle[0]
			if(n2==None):
				n2=middle[-1]
			if(len(n1)>len(n2)):
				middle=n1
			else:
				middle=n2
			print(suffix+middle+prefix)
		else:
			print(suffix+prefix)

# for i in dicti:
# 	temp=0
# 	for j in helper:
# 		if(j[0]<=i[0] and j[1]<=i[1]):
# 			temp+=(i[0]-j[0]+1)*(i[1]-j[1]+1)
# 		if(j[1]<=i[0] and j[0]<=i[1] and j[0]!=j[1]):
# 			temp+=(i[0]-j[1]+1)*(i[1]-j[0]+1)
# 	count+=temp*dicti[i]

# def all_partitions(string):
#     for cutpoints in range(1 << (len(string)-1)):
#         result = []
#         lastcut = 0
#         for i in range(len(string)-1):
#             if (1<<i) & cutpoints != 0:
#                 result.append(string[lastcut:(i+1)])
#                 lastcut = i+1
#         result.append(string[lastcut:])
#         yield result

# maxyet=0
# store={'h': -6, 'e': -7, 'l': -8, 'o': 3, 'he': 3, 'hel': -3, 'el': 0, 'hell': 6, 'ell': -5, 'll': 10, 'hello': -3, 'ello': -8, 'llo': 9, 'lo': -6}

# def quality(stri):
# 	return store[stri]

# for partition in all_partitions("hel"):
#     temp=0
#     for i in partition:
#     	temp+=quality(i)
#     if(temp>maxyet):
#     	print(partition)
#     	maxyet=temp

# print(maxyet)


def ispelin(ss,i,j):
    while i<j:
        if(ss[i]!=ss[j]):
            return False
        i+=1
        j-=1
    return True

def fun1(ss):
    i=0
    j=len(ss)-1

    while i<=j:
        #print(i,j)
        if(ss[i]==ss[j]):
            if(ispelin(ss,i,j)):
                return [i,j]
        j-=1
def fun2(ss):
    i=0
    j=len(ss)-1
    while i<=j:
        if(ss[i]==ss[j]):
            if(ispelin(ss,i,j)):
                return [i,j]
        i+=1
t=int(input())
while t:
    s=input()
    i=0
    n=len(s)
    j=n-1
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        #print("lol")
    #print(i,j)
    ss=s[i:j+1]
    #print(ss)
    ii1,jj1=fun1(ss)
    ii2,jj2=fun2(ss)
    if(jj2-ii2>jj1-ii1):
        #print(ii2,jj2,i,j,s[:i])
        res=s[:i]+s[i+ii2:i+jj2]+s[j:]
    else:
        #print(ii1,jj1,i,j,s[:i])
        res=s[:i]+s[i+ii1:i+jj1+1]+s[j+1:]
    #print(ii1,jj1)

    print(res)
    t-=1


def ispelin(ss,i,j):
    while i<j:
        if(ss[i]!=ss[j]):
            return False
        i+=1
        j-=1
    return True

def fun1(ss):
    i=0
    j=len(ss)-1

    while i<=j:
        #print(i,j)
        if(ss[i]==ss[j]):
            if(ispelin(ss,i,j)):
                return [i,j]
        j-=1
def fun2(ss):
    i=0
    j=len(ss)-1
    while i<=j:
        if(ss[i]==ss[j]):
            if(ispelin(ss,i,j)):
                return [i,j]
        i+=1
t=int(input())
while t:
    s=input()
    i=0
    n=len(s)
    j=n-1
    while i<j and s[i]==s[j]:
        i+=1
        j-=1
        #print("lol")
    #print(i,j)
    ss=s[i:j+1]
    #print(ss)
    ii1,ii2,jj1,jj2=0,0,-1,-1
    if(i<=j):
        ii1,jj1=fun1(ss)
        ii2,jj2=fun2(ss)
    if(jj2-ii2>jj1-ii1):
        #print(ii2,jj2,i,j,s[:i])
        res=s[:i]+s[i+ii2:i+jj2]+s[j:]
    else:
        #print(ii1,jj1,i,j,s[:i])
        res=s[:i]+s[i+ii1:i+jj1+1]+s[j+1:]
    #print(ii1,jj1)

    print(res)
    t-=1


def z_function(s,z):
    n=len(s)

    l,r,k=0,0,0
    for i in range(1,n):
        if(i>r):
            l,r=i,i
            while r<n and s[r-l]==s[r]:
                r+=1
            z[i]=r-l
            r-=1
        else:
            k=i-l
            if(z[k]<r-i+1):
               z[i]=z[k]
            else:
                l=i
                while r<n and s[r-l]==s[r]:
                    r+=1
                z[i]=r-l
                r-=1

import sys
input=sys.stdin.readline
t=int(input())
def solve(ss,res):

    mx=0
    #print(ss)
    z=[0]*len(ss)
    z_function(ss,z)
    #print(ss)
    #print(z)
    ls=len(z)
    for i in range(len(z)-1,-1,-1):
        #print(z[i],ls-i+1)
        if(z[i]==ls-i):
            mx=max(mx,z[i])
    #print(mx)
    for i in range(mx):
        res.append(ss[i])
    nn=len(res)
    for i in range(nn-mx-1,-1,-1):
        res.append(res[i])
    return "".join(res)

while t:

    res1=[]
    res2=[]
    s=input().split()[0]
    n=len(s)
    if(n==1):
        print(s)
    else:
        i=0
        j=n-1
        while i<j:
            if(s[i]==s[j]):
                res1.append(s[i])
                res2.append(s[i])
            else:
                break
            i+=1
            j-=1
        ss=s[i:j]
        ss=ss+'*'+ss[::-1]
        s1=solve(ss,res1)
        ss=s[i:j+1]
        ss=ss[::-1]+'*'+ss
        s2=solve(ss,res2)
        if(len(s1)>=len(s2)):
            print(s1)
        else:
            print(s2)
    t-=1


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

for _ in range(t):
    s = input()
    maxstr = ""
    maxsize = 0

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    s = s[::-1]

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    if maxsize == 0:
        print(s[0])
    else:
        print(maxstr)


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

def find_palindrome(cropped_string):
    smax = ""
    # len , current , type
    prog = []
    # len , type
    final = [0, 0]
    cur = 0

    while (cur < len(cropped_string)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if cropped_string[h] == cropped_string[cur]:
                x[1] -= 1
                if x[1] == -1:
                    final = [x[0],x[2]]
                else:
                    prog2.append(x)

        # abccba
        if cur > 0:
            if cropped_string[cur] == cropped_string[cur-1]:
                prog2.append([cur, cur-2, 0])
        # abcba
        if cur > 1:
            if cropped_string[cur] == cropped_string[cur-2]:
                prog2.append([cur-1, cur-3, 1])

        prog = prog2
        cur += 1
        # print(cropped_string[:cur])
        # print(cur, prog, final)

    # print(f"{final=}")

    olen = final [0] * 2 + final[1]

    return cropped_string[:olen]
    # return smax

for _ in range(t):

    s = input()
    r = s[::-1]

    i = 0
    while i < (len(s)//2):
        if s[i] == r[i]:
            i += 1
        else:
            break

    if i*2 == len(s):
        # print("ans")
        print(s)
        continue

    crop = s[i:len(s)-i]
    side = i

    # print(f"{crop=} {side=}")

    left = find_palindrome(crop)
    # print("_"*10)
    right = find_palindrome(crop[::-1])
    # print("left, right")
    # print(left,right)

    if not left and not right :
        mid = crop[0]
    elif len(left)>len(right):
        mid = left
    else:
        mid = right
    # print("ans")
    print(s[:i] +mid + s[:i][::-1])


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

def find_palindrome(cropped_string):
    smax = ""
    # len , current , type
    prog = []
    # len , type
    final = [0, 0]
    cur = 0

    while (cur < len(cropped_string)):
        prog2 = []
        # print(cur,prog,final)
        for i, x in enumerate(prog):
            h = x[1]
            # print("x",x)
            # print(cropped_string[h],cropped_string[cur])
            if h == -1:
                if final[0] < x[0] or (final[0] == x[0] and x[2] ==1):
                    final = [x[0],x[2]]

            elif cropped_string[h] == cropped_string[cur]:
                x[1] -= 1
                if x[1] == -1:
                    # print(f"final",x[0],final)
                    if final[0] < x[0] or (final[0] == x[0] and x[2] ==1):
                        final = [x[0],x[2]]
                else:
                    prog2.append(x)

        # abccba
        if cur > 0:
            if cropped_string[cur] == cropped_string[cur-1]:
                prog2.append([cur, cur-2, 0])
        # abcba
        if cur > 1:
            if cropped_string[cur] == cropped_string[cur-2]:
                prog2.append([cur-1, cur-3, 1])

        prog = prog2
        cur += 1
        # print(cropped_string[:cur])
        # print(cur, prog, final)
        # print("_"*22)

    # print(f"{final=}")

    olen = final [0] * 2 + final[1]

    return cropped_string[:olen]
    # return smax

for _ in range(t):

    s = input()
    r = s[::-1]

    i = 0
    while i < (len(s)//2):
        if s[i] == r[i]:
            i += 1
        else:
            break

    if i*2 == len(s):
        # print("ans")
        print(s)
        continue

    crop = s[i:len(s)-i]
    side = i

    # print(f"{crop=} {side=}")

    left = find_palindrome(crop)
    # print("_"*10)
    right = find_palindrome(crop[::-1])
    # print("left, right")
    # print(left,right)

    if not left and not right :
        mid = crop[0]
    elif len(left)>len(right):
        mid = left
    else:
        mid = right
    # print("ans")
    print(s[:i] +mid + s[:i][::-1])


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

for _ in range(t):
    s = input()
    i=0
    while i < (len(s)//2):

        print( s[:i+1] , s[:-i-2:-1])
        if s[:i+1] == s[:-i-2:-1]:
            i+=1
        else:
            break
    # print("i is :", i )

    maxstr = s[:i+1]+s[:i][::-1]

    # print("temp",maxstr)
    maxsize = i*2+1

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    s = s[::-1]

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    if maxsize == 0:
        print(s[0])
    else:
        print(maxstr)


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

def find_palindrome(cropped_string):
    smax = ""
    # len , current , type
    prog = []
    # len , type
    final = [0, 0]
    cur = 0

    while (cur < len(cropped_string)):
        prog2 = []
        # print(cur,prog,final)
        for i, x in enumerate(prog):
            h = x[1]
            # print("x",x)
            # print(cropped_string[h],cropped_string[cur])
            if h == -1:
                if final[0] < x[0]:
                    final = [x[0],x[2]]

            elif cropped_string[h] == cropped_string[cur]:
                x[1] -= 1
                if x[1] == -1:
                    # print(f"final",x[0],final)
                    if final[0] < x[0]:
                        final = [x[0],x[2]]
                else:
                    prog2.append(x)

        # abccba
        if cur > 0:
            if cropped_string[cur] == cropped_string[cur-1]:
                prog2.append([cur, cur-2, 0])
        # abcba
        if cur > 1:
            if cropped_string[cur] == cropped_string[cur-2]:
                prog2.append([cur-1, cur-3, 1])

        prog = prog2
        cur += 1
        # print(cropped_string[:cur])
        # print(cur, prog, final)
        # print("_"*22)

    # print(f"{final=}")

    olen = final [0] * 2 + final[1]

    return cropped_string[:olen]
    # return smax

for _ in range(t):

    s = input()
    r = s[::-1]

    i = 0
    while i < (len(s)//2):
        if s[i] == r[i]:
            i += 1
        else:
            break

    if i*2 == len(s):
        # print("ans")
        print(s)
        continue

    crop = s[i:len(s)-i]
    side = i

    # print(f"{crop=} {side=}")

    left = find_palindrome(crop)
    # print("_"*10)
    right = find_palindrome(crop[::-1])
    # print("left, right")
    # print(left,right)

    if not left and not right :
        mid = crop[0]
    elif len(left)>len(right):
        mid = left
    else:
        mid = right
    # print("ans")
    print(s[:i] +mid + s[:i][::-1])


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

def find_palindrome(cropped_string):
    smax = ""
    # len , current , type
    prog = []
    # len , type
    final = [0, 0]
    cur = 0

    while (cur < len(cropped_string)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if h == -1:
                final = [x[0],x[2]]
            if cropped_string[h] == cropped_string[cur]:

                x[1] -= 1
                if x[1] == -1:
                    final = [x[0],x[2]]
                else:
                    prog2.append(x)

        # abccba
        if cur > 0:
            if cropped_string[cur] == cropped_string[cur-1]:
                prog2.append([cur, cur-2, 0])
        # abcba
        if cur > 1:
            if cropped_string[cur] == cropped_string[cur-2]:
                prog2.append([cur-1, cur-3, 1])

        prog = prog2
        cur += 1
        # print(cropped_string[:cur])
        # print(cur, prog, final)

    # print(f"{final=}")

    olen = final [0] * 2 + final[1]

    return cropped_string[:olen]
    # return smax

for _ in range(t):

    s = input()
    r = s[::-1]

    i = 0
    while i < (len(s)//2):
        if s[i] == r[i]:
            i += 1
        else:
            break

    if i*2 == len(s):
        # print("ans")
        print(s)
        continue

    crop = s[i:len(s)-i]
    side = i

    # print(f"{crop=} {side=}")

    left = find_palindrome(crop)
    # print("_"*10)
    right = find_palindrome(crop[::-1])
    # print("left, right")
    # print(left,right)

    if not left and not right :
        mid = crop[0]
    elif len(left)>len(right):
        mid = left
    else:
        mid = right
    # print("ans")
    print(s[:i] +mid + s[:i][::-1])


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

for _ in range(t):
    s = input()
    i=0
    while i < (len(s)//2):

        # print( s[:i+1] , s[:-i-2:-1])
        if s[:i+1] == s[:-i-2:-1]:
            i+=1
        else:
            break
    # print("i is :", i )

    maxstr = s[:i+1]+s[:i][::-1]

    # print("temp",maxstr)
    maxsize = i*2+1

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    s = s[::-1]

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    if maxsize == 0:
        print(s[0])
    else:
        print(maxstr)


import sys
# from itertools import permutations, combinations
# from collections import deque
# import math
# from bisect import bisect

# FAST INPUT for submit
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline

# FAST OUTPUT for submit
#
#

def in1():
    return int(input())

def in3():
    return map(int, input().split())

def inx():
    return [int(_) for _ in input().split()]

t = in1()

for _ in range(t):
    s = input()
    i=0
    while i < (len(s)//2):

        # print( s[:i+1] , s[:-i-2:-1])
        if s[:i+1] == s[:-i-2:-1]:
            i+=1
        else:
            break
    # print("i is :", i )

    maxstr = s[:i+1]+s[:i][::-1]
    if len(maxstr) > len(s):
        print(s)
        continue
    # print("temp",maxstr)
    maxsize = len(maxstr)

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            if x[1] == -1:
                done.append(x)
                continue
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    s = s[::-1]

    prog = []
    done = []
    cur = 0
    while (cur < len(s)):
        prog2 = []
        for i, x in enumerate(prog):
            if x[1] == -1:
                done.append(x)
                continue
            h = x[1]
            if s[h] == s[cur]:
                x[1] -= 1
                if x[1] == -1:
                    done.append(x)
                else:
                    prog2.append(x)

            else:
                done.append(x)
        if cur > 0:
            if s[cur] == s[cur-1]:
                prog2.append([cur,cur-2,0])
        if cur > 1:
            if s[cur] == s[cur-2]:
                prog2.append([cur,cur-3,1])

        prog = prog2
        cur += 1
        # print(s[:cur])
        # print(cur, prog, done)

    for d in done:
        if d[1] == -1:
            t =  d[0]*2-d[2]
            if t> maxsize:
                maxsize = t
                maxstr = s[:maxsize]
                # print(f"{maxstr=}")
        else:
            # print(s[:-d[1]-2:-1] ,"  ", s[:d[1]+1])
            if s[:-d[1]-2:-1] == s[:d[1]+1]:
                t = d[0] * 2 - d[2]
                if t>maxsize:

                    maxsize = t
                    maxstr = s[:t-d[1]-1]+s[-d[1]-1:]
                    # print(f"{maxstr=}")

    if maxsize == 0:
        print(s[0])
    else:
        print(maxstr)


def find_pal_prefix(s):
    if not s:
        return s

    res = s[0]
    for i in range(1, len(s)):
        s1 = s[:i]
        s2 = s1[::-1]
        if s1 == s2:
            res = s1
    return res

def solve():
    s1 = input().strip()
    s2 = s1[::-1]

    a = ""
    b = ""
    p = 0
    for p in range(len(s1) // 2):
        next_a = s1[p]
        next_b = s2[p]
        if next_a == next_b:
            a += next_a
            b += next_b
        else:
            break
    else:
        if len(s1) % 2 == 1:
            a += s1[len(s1) // 2]

    s = s1
    if len(b) == 0:
        s = s[len(a):]
    else:
        s = s[len(a):-len(b)]

    a_plus = find_pal_prefix(s)
    b_plus = find_pal_prefix(s[::-1])

    if len(a_plus) > len(b_plus):
        a += a_plus
    else:
        b += b_plus

    two_sided_pal = a + b[::-1]
    return two_sided_pal

def main():
    t = int(input())
    for _ in range(t):
        print(solve())

if __name__ == "__main__":
    main()


def find_pal_prefix(s):
    if not s:
        return s

    res = s[0]
    for i in range(1, len(s)):
        s1 = s[:i]
        s2 = s1[::-1]
        if s1 == s2:
            res = s1
    return res

def solve():
    s1 = input().strip()
    s2 = s1[::-1]

    a = ""
    b = ""
    p = 0
    for p in range(len(s1) // 2):
        next_a = s1[p]
        next_b = s2[p]
        if next_a == next_b:
            a += next_a
            b += next_b
        else:
            break
    else:
        if len(s1) % 2 == 1:
            a += s1[p]

    s = s1
    if len(b) == 0:
        s = s[len(a):]
    else:
        s = s[len(a):-len(b)]

    a_plus = find_pal_prefix(s)
    b_plus = find_pal_prefix(s[::-1])

    if len(a_plus) > len(b_plus):
        a += a_plus
    else:
        b += b_plus

    two_sided_pal = a + b[::-1]
    return two_sided_pal

def main():
    t = int(input())
    for _ in range(t):
        print(solve())

if __name__ == "__main__":
    main()


t=int(input())
for _ in range(t):
    s=input()
    n=len(s)
    left=0
    right=n-1
    while(left<right):
        if s[left]==s[right]:
            left+=1
            right-=1
        else:
            break
    s1=s[left:right+1]
    max_len=0
    ans=''
    for i in range(len(s1)):
        c=s1[i:]
        if c==c[::-1] and len(c)>max_len:
            ans=c
            max_len=len(c)
    for i in range(len(s1),-1,-1):
        c=s1[:i]
        if c==c[::-1] and len(c)>max_len:
            ans=c
            max_len=len(c)
    print(s[:left]+ans+s[right+1:])


t=int(input())
for _ in range(t):
    s=input()
    n=len(s)
    q=[]
    for i in range(n):
        for j in range(i,n+1):
            c=s[:i]+s[j:]
            #print(c)
            if c==c[::-1]:
                q.append(c)
    mx=0
    for i in q:
        mx=max(mx,len(i))
    if mx==0:
        print(s[i])
    else:
        for i in q:
            if len(i)==mx:
                print(i)
                break


def pali(a):
    s,e='',''
    for i in range(1,len(a)-1):
        if a[i]==a[0] and a[:i+1]==a[:i+1][::-1]:
            s=a[:i+1]
        if a[i]==a[-1] and a[i:]==a[i:][::-1]:
            e=a[i:]
    if s=='' and e=='':
        return a[0]
    if len(s)>len(e):
        return s
    return e

for _ in range(int(input())):
    s=input()
    if s==s[::-1]:
        print(s)
        continue
    i=-1;j=len(s)
    while i<j and s[i+1]==s[j-1]:
        i+=1
        j-=1
    print(s[:i+1]+pali(s[i+1:j])+s[j:])


def pali(a):
    s='';e='';
    for i in range(1,len(a)-1):
        if a[i]==a[0] and a[:i+1]==a[:i+1][::-1]:
            s=a[:i+1]
        if a[i]==a[-1] and a[i:]==a[i:][::-1]:
            e=a[i:]
    if s=='' and e=='':
        return a[0]
    if len(s)>len(e):
        return s
    return e

for _ in range(int(input())):
    s=input()
    if s==s[::-1]:
        print(s)
        continue
    i=-1;j=len(s)
    while i<j and s[i+1]==s[j-1]:
        i+=1
        j-=1
    print(s[:i+1]+pali(s[i+1:j])+s[j:])


def pali(a):
    s,e='',''
    for i in range(1,len(a)-1):
        if a[i]==a[0] and a[:i+1]==a[:i+1][::-1]:
            s=a[:i+1]
        if e=='' and a[i]==a[-1] and a[i:]==a[i:][::-1]:
            e=a[i:]
    if s=='' and e=='':
        return a[0]
    if len(s)>len(e):
        return s
    return e

for _ in range(int(input())):
    s=input()
    if s==s[::-1]:
        print(s)
        continue
    i=-1;j=len(s)
    while i<j and s[i+1]==s[j-1]:
        i+=1
        j-=1
    print(s[:i+1]+pali(s[i+1:j])+s[j:])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s[:ans1])
            else:
                print(s[0])

        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s[:ans2])
            else:
                print(s[0])
    else:
        i=0
        j=n-1
        s1=s[0:]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        ans1=max(ans1[N//2+2:])
        ans2=max(ans2[N//2+2:])
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
            else:
                print(s1[0:i]+s1[0:i][::-1])
        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans2] + s1[0:i][::-1])
            else:
                print(s1[0:i]+s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

def maximum_Length_Palindrome(Z,n):
    for i in range(n):
        if Z[i]==n-i:
            return Z[i]

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)

        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            print(s[:ans2])
    else:
        i=0
        j=n-1
        s1=s[0:n]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)
        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                left=i
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

def maximum_Length_Palindrome(Z,n):
    #print(Z)
    for i in range(n):
        if Z[i]==n-i:
            return Z[i]

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)

        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            print(s[:ans2])
    else:
        i=0
        j=n-1
        s1=s[0:n]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)
        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans2] + s1[0:i][::-1])


def Z_Array(l):
    left=0
    right=0
    n=len(l)
    Z=[0]*n
    for i in range(1,n):
        if i>right:
            left=i
            right=i
            while (right<n and l[right]==l[right-left]):
                right+=1
            Z[i]=right-left
            right-=1
        else:
            k=i-left
            if (Z[k]+i-1)<right:
                Z[i]=Z[k]
            else:
                while (right<n and l[right]==l[right-left]):
                    right+=1
                Z[i]=right-left
                right-=1
    return Z

def Z_Algorithm(pattern, text):
    l=[p for p in pattern]
    l.append('#')
    l.extend([t for t in text])
    Z=Z_Array(l)
    return Z

def maximum_Length_Palindrome(Z,n):
    max_len=0
   # print(Z)
    for i in range(n):
        if Z[i]==n-i:
            if Z[i]>max_len:
                max_len=Z[i]
    return max_len

for _ in range(int(input())):
    s=input()
    n=len(s)
    N=2*n+1
    if n==1 or s==s[::-1]:
        print(s)
    elif s[0]!=s[-1]:
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)

        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            print(s[:ans1])
        else:
            s=s[::-1]
            print(s[:ans2])
    else:
        i=0
        j=n-1
        s1=s[0:n]
        while i<j:
            if s[i]!=s[j]:
                break
            else:
                i+=1
                j-=1
        s=s[i:j+1]
        n=len(s)
        N=2*n+1
        ans1=Z_Algorithm(s, s[::-1])
        ans2=Z_Algorithm(s[::-1], s)
        #print(ans1,ans2)
        ans1=maximum_Length_Palindrome(ans1[N//2+1:],n)
        ans2=maximum_Length_Palindrome(ans2[N//2+1:],n)
        #print(ans1,ans2)
        if ans1>=ans2:
            s=s[:ans1]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans1] + s1[0:i][::-1])
        else:
            s=s[::-1]
            s=s[:ans2]
            if s==s[::-1]:
                print(s1[0:i] + s[:ans2] + s1[0:i][::-1])