Skip to content

Instantly share code, notes, and snippets.

@satyajeetkrjha
Last active July 11, 2022 08:46
Show Gist options
  • Save satyajeetkrjha/771a48b9557bdf9a480e337892d6084b to your computer and use it in GitHub Desktop.
Save satyajeetkrjha/771a48b9557bdf9a480e337892d6084b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
string line;
string res;
stack<char> st ;
while (getline(cin, line)) {
int sz = line.size();
for(int i =0 ;i<sz;i++){
char ch = line[i];
if(ch == '(' || ch == '[' || ch == '{' || ch == ')' || ch == '}' || ch == ']'){
res+= ch;
}
}
}
int ressize = res.size();
for(int i =0 ;i<ressize;i++){
char ch = res[i];
if(ch == '(' || ch == '{' || ch == '['){
st.push(res[i]);
}
else{
if(st.empty()){
cout <<"invalid"<< endl;
return 0;
}
char topchar = st.top();
st.pop();
if(topchar == '(' && ch !=')'){
cout <<"invalid"<< endl;
return 0;
}
if(topchar == '{' && ch !='}'){
cout <<"invalid"<< endl;
return 0;
}
if(topchar == '[' && ch !=']'){
cout <<"invalid"<<endl;
return 0;
}
}
}
if(st.empty()){
cout <<"valid"<< endl;
return 0;
}
else{
cout <<"invalid"<< endl;
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment