Guest User

Untitled

a guest
Jun 24th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. //
  2. // Created by jrv on 6/23/18.
  3. //
  4.  
  5. // Author : Jibin Rajan Varghese
  6. //
  7. // Problems from CTCI
  8.  
  9. #include<iostream> // Shorter way would be
  10. #include<vector> // #include<bits/stdc++.h>
  11. #include<math.h> // using namespace std;
  12. #include<algorithm> // but namespaces are dangerous,
  13. #include<limits> // and we like efficient code :)
  14. #include<string>
  15.  
  16. #include<unordered_map>
  17. #include<stack> //Common stuff; remove if not needed
  18. #include<queue> //Uncommon stuff; add if needed
  19.  
  20. using std::cin;
  21. using std::cout;
  22. using std::endl;
  23. using std::getline;
  24. using std::vector;
  25. using std::stack;
  26. using std::queue;
  27. using std::string;
  28. using std::to_string;
  29.  
  30.  
  31. class Solution {
  32. public:
  33. int scoreOfParentheses(string S) {
  34.  
  35. vector<string> expr;
  36.  
  37. for(int i = 0; i < S.size(); ++i)
  38. {
  39. string s;
  40. s.push_back(S[i]);
  41. expr.push_back(s);
  42. }
  43.  
  44. return reduce(expr);
  45.  
  46.  
  47.  
  48. }
  49.  
  50.  
  51. int reduce(vector<string> &expr)
  52. {
  53.  
  54.  
  55. if(expr.size()==1 && isdigit(expr[0][0]))
  56. return stoi(expr[0]);
  57.  
  58. for( int i = 0; i < expr.size(); ++i)
  59. cout<<expr[i]<<" ";
  60.  
  61. cout<<endl;
  62.  
  63. vector<string> reduced;
  64. int i = 0;
  65. while( i < expr.size())
  66. {
  67.  
  68. // Handle Single Bracket ()
  69.  
  70.  
  71. if(i+1 < expr.size() && expr[i] == "(" && expr[i+1] == ")" )
  72. {
  73. string s = "1";
  74. reduced.push_back(s);
  75. i+=2 ;
  76. continue;
  77.  
  78. }
  79.  
  80. // Handle list of numbers
  81.  
  82.  
  83. int count = 0;
  84. int prev = i;
  85. while(i < expr.size() && isdigit(expr[i][0]) )
  86. {
  87. count+= stoi(expr[i]);
  88. ++i;
  89.  
  90. }
  91. int current = i;
  92.  
  93. if(current>prev) // multiple numbers have been added
  94. {
  95. reduced.push_back(to_string(count));
  96. continue;
  97. }
  98.  
  99. // Handle single nested number and bracket (4) = 8
  100.  
  101. if ( i+2 < expr.size() && expr[i] == "(" && isdigit( expr[i+1][0]) && expr[i+2] == ")" )
  102. {
  103. reduced.push_back( to_string( 2 * stoi(expr[i+1])));
  104. i+=3;
  105. continue;
  106. }
  107.  
  108. // Else push whatever
  109. if(i<expr.size())
  110. reduced.push_back(expr[i]);
  111. ++i;
  112.  
  113. }
  114.  
  115. return reduce(reduced);
  116.  
  117. }
  118. };
  119.  
  120. int main(){
  121. cout<<" LC856 Score of Parantheses"<<std::endl; // Change to current problem
  122.  
  123. Solution s;
  124. cout<< s.scoreOfParentheses("(()())()");
  125.  
  126. return 0;
  127. }
Add Comment
Please, Sign In to add comment