Copy and push back

include <bits/stdc++.h>
using namespace std;
void input(int a,int n)
{
for(int i=0;i<n;i++)
cin>>a[i];
}

define ull unsigned long long
define ll long long

int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t–)
{
int n;
cin>>n;
string s;
cin>>s;
string ans;
ans = s[0];
int flag = 1;
while(ans.length()+1<=n || ans.length()*2<=n)
{
if(flag == 1)
{
ans += ans;
//cout<<ans<<endl;
flag = 0;
}
else
{
string temp1 , temp2;
temp1 = ans+ans;
temp2 = ans;
temp2 += s[ans.length()];
if(temp1 == s.substr(0,temp1.length()))
{
ans = temp1;
//cout<<ans<<endl;

            }
            else if(temp2 == s.substr(0,temp2.length()))
            {
                ans = temp2;
                //cout<<ans<<endl;
                flag = 1;
            }
            else
            {
                break;
            }
            
        }
    }
    if(ans == s)cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
     
}
return 0;

}
why it is giving wrong answer???