Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Created by jrv on 6/23/18.
- //
- // Author : Jibin Rajan Varghese
- //
- // Problems from CTCI
- #include<iostream> // Shorter way would be
- #include<vector> // #include<bits/stdc++.h>
- #include<math.h> // using namespace std;
- #include<algorithm> // but namespaces are dangerous,
- #include<limits> // and we like efficient code :)
- #include<string>
- #include<unordered_map>
- #include<stack> //Common stuff; remove if not needed
- #include<queue> //Uncommon stuff; add if needed
- using std::cin;
- using std::cout;
- using std::endl;
- using std::getline;
- using std::vector;
- using std::stack;
- using std::queue;
- using std::string;
- using std::to_string;
- class Solution {
- public:
- int scoreOfParentheses(string S) {
- vector<string> expr;
- for(int i = 0; i < S.size(); ++i)
- {
- string s;
- s.push_back(S[i]);
- expr.push_back(s);
- }
- return reduce(expr);
- }
- int reduce(vector<string> &expr)
- {
- if(expr.size()==1 && isdigit(expr[0][0]))
- return stoi(expr[0]);
- for( int i = 0; i < expr.size(); ++i)
- cout<<expr[i]<<" ";
- cout<<endl;
- vector<string> reduced;
- int i = 0;
- while( i < expr.size())
- {
- // Handle Single Bracket ()
- if(i+1 < expr.size() && expr[i] == "(" && expr[i+1] == ")" )
- {
- string s = "1";
- reduced.push_back(s);
- i+=2 ;
- continue;
- }
- // Handle list of numbers
- int count = 0;
- int prev = i;
- while(i < expr.size() && isdigit(expr[i][0]) )
- {
- count+= stoi(expr[i]);
- ++i;
- }
- int current = i;
- if(current>prev) // multiple numbers have been added
- {
- reduced.push_back(to_string(count));
- continue;
- }
- // Handle single nested number and bracket (4) = 8
- if ( i+2 < expr.size() && expr[i] == "(" && isdigit( expr[i+1][0]) && expr[i+2] == ")" )
- {
- reduced.push_back( to_string( 2 * stoi(expr[i+1])));
- i+=3;
- continue;
- }
- // Else push whatever
- if(i<expr.size())
- reduced.push_back(expr[i]);
- ++i;
- }
- return reduce(reduced);
- }
- };
- int main(){
- cout<<" LC856 Score of Parantheses"<<std::endl; // Change to current problem
- Solution s;
- cout<< s.scoreOfParentheses("(()())()");
- return 0;
- }
Add Comment
Please, Sign In to add comment