In this question firstly user will give the number of test cases, for each of the test cases users enter a string like [{()}]. This code if s[i] value equal to any left bracket like '(', '[', '{' then i added it's right bracket into ans string otherwise we have to compare last added character in ans with current s[i] character.
#include <bits/stdc++.h>
using namespace std;
string isBalanced(string s) {
string ans;
int j=-1;
for(int i=0; i<s.length(); i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
if(s[i]=='(')
ans.push_back((char)(s[i]+1));
else ans.push_back((char)(s[i]+2));
j++;
}
else if(s[j]==s[i] && i>0){
ans.pop_back();
j--;
}
}
if(ans.empty()) return "YES";
else return "NO";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
string s;
getline(cin, s);
string result = isBalanced(s);
fout << result << "\n";
}
fout.close();
return 0;
}