leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0856.cpp (734B)


      1 
      2 // Stack solution
      3 class Solution {
      4   public:
      5     int scoreOfParentheses(const string &s) {
      6         stack<int> st;
      7         int score = 0;
      8         for (const char c : s) {
      9             if (c == '(')
     10                 st.push(score), score = 0;
     11             else {
     12                 score = score ? 2 * score : 1;
     13                 score += st.top();
     14                 st.pop();
     15             }
     16         }
     17         return score;
     18     }
     19 };
     20 
     21 // O(1) memory solution
     22 class Solution {
     23   public:
     24     int scoreOfParentheses(const string &s) {
     25         int res = 0, l = 0;
     26         for (int i = 0; i < s.size(); i++) {
     27             l += s[i] == '(' ? 1 : -1;
     28             if (s[i] == ')' && s[i - 1] == '(') res += 1 << l;
     29         }
     30         return res;
     31     }
     32 };