Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <stack>
- #include <utility>
- using namespace std;
- bool isOpenParenthesis(char s){
- return (s=='(' || s=='{' || s=='[');
- }
- bool isClosedParenthesis(char s){
- return (s==')' || s=='}' || s==']');
- }
- bool notParenthesis(char s){
- return !isOpenParenthesis(s) && !isClosedParenthesis(s);
- }
- char matchParenthesis(char s){
- if(s=='(')
- return ')';
- else if(s=='{')
- return '}';
- else if(s=='[')
- return ']';
- else
- return '\0';
- }
- bool isBalanced(string s, vector<int> &matchPosOpen) {
- // Complete this function
- stack<pair<char,int>> match;
- char curr;
- for(int i=0;i<s.length();i++){
- curr=s[i];
- if(isOpenParenthesis(curr))
- match.push(make_pair(curr,i));
- else if(isClosedParenthesis(curr)){
- if(match.empty())
- return false;
- auto top=match.top();
- if(curr!=matchParenthesis(top.first))
- return false;
- else{
- matchPosOpen[top.second]=i;
- match.pop();
- }
- }
- }
- return match.empty();
- }
- string reverseParenthesisHelper(string s, int start, int end, bool inParenthesis, vector<int> &matchPosOpen){
- if(s=="" || start==end)
- return "";
- else{
- char curr;
- string subsoln,soln="";
- int i=start;
- while(i<end){
- curr=s[i];
- if(isOpenParenthesis(curr)){
- subsoln= reverseParenthesisHelper(s,i+1,matchPosOpen[i],true, matchPosOpen);
- soln+=subsoln;
- i=matchPosOpen[i];
- }else
- soln+=curr;
- i++;
- }
- if(inParenthesis){
- reverse(soln.begin(),soln.end());
- return soln;
- }else
- return soln;
- }
- }
- string reverseParenthesis(string s){
- vector<int> matchPosOpen(s.length());
- if(isBalanced(s,matchPosOpen)){
- return reverseParenthesisHelper(s,0,s.length(),false,matchPosOpen);
- }else{
- return "Invalid Input";
- }
- }
- int main() {
- int t;
- cin >> t;
- for(int a0 = 0; a0 < t; a0++){
- string s;
- cin >> s;
- cout<< reverseParenthesis(s)<<endl;
- }
- return 0;
- }
- /*
- 8
- ({()((
- {[()]}
- (a)
- ()a
- a()
- abc
- a((br)cd)ef(ghi)
- a((br(pq(m)))cd)ef(ghi)
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement