Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <stack>
  3. #include <utility>
  4.  
  5. using namespace std;
  6.  
  7. bool isOpenParenthesis(char s){
  8. return (s=='(' || s=='{' || s=='[');
  9. }
  10.  
  11. bool isClosedParenthesis(char s){
  12. return (s==')' || s=='}' || s==']');
  13. }
  14.  
  15. bool notParenthesis(char s){
  16. return !isOpenParenthesis(s) && !isClosedParenthesis(s);
  17. }
  18.  
  19. char matchParenthesis(char s){
  20. if(s=='(')
  21. return ')';
  22. else if(s=='{')
  23. return '}';
  24. else if(s=='[')
  25. return ']';
  26. else
  27. return '\0';
  28. }
  29.  
  30. bool isBalanced(string s, vector<int> &matchPosOpen) {
  31. // Complete this function
  32. stack<pair<char,int>> match;
  33. char curr;
  34. for(int i=0;i<s.length();i++){
  35. curr=s[i];
  36. if(isOpenParenthesis(curr))
  37. match.push(make_pair(curr,i));
  38. else if(isClosedParenthesis(curr)){
  39. if(match.empty())
  40. return false;
  41. auto top=match.top();
  42. if(curr!=matchParenthesis(top.first))
  43. return false;
  44. else{
  45. matchPosOpen[top.second]=i;
  46. match.pop();
  47. }
  48.  
  49. }
  50. }
  51. return match.empty();
  52. }
  53.  
  54. string reverseParenthesisHelper(string s, int start, int end, bool inParenthesis, vector<int> &matchPosOpen){
  55. if(s=="" || start==end)
  56. return "";
  57. else{
  58. char curr;
  59. string subsoln,soln="";
  60. int i=start;
  61. while(i<end){
  62. curr=s[i];
  63. if(isOpenParenthesis(curr)){
  64. subsoln= reverseParenthesisHelper(s,i+1,matchPosOpen[i],true, matchPosOpen);
  65. soln+=subsoln;
  66. i=matchPosOpen[i];
  67. }else
  68. soln+=curr;
  69. i++;
  70. }
  71. if(inParenthesis){
  72. reverse(soln.begin(),soln.end());
  73. return soln;
  74. }else
  75. return soln;
  76.  
  77. }
  78. }
  79.  
  80. string reverseParenthesis(string s){
  81. vector<int> matchPosOpen(s.length());
  82. if(isBalanced(s,matchPosOpen)){
  83. return reverseParenthesisHelper(s,0,s.length(),false,matchPosOpen);
  84. }else{
  85. return "Invalid Input";
  86. }
  87. }
  88.  
  89. int main() {
  90. int t;
  91. cin >> t;
  92. for(int a0 = 0; a0 < t; a0++){
  93. string s;
  94. cin >> s;
  95. cout<< reverseParenthesis(s)<<endl;
  96. }
  97. return 0;
  98. }
  99.  
  100. /*
  101. 8
  102. ({()((
  103. {[()]}
  104. (a)
  105. ()a
  106. a()
  107. abc
  108. a((br)cd)ef(ghi)
  109. a((br(pq(m)))cd)ef(ghi)
  110. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement