leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0856.cpp (734B)
0 1 // Stack solution 2 class Solution { 3 public: 4 int scoreOfParentheses(const string &s) { 5 stack<int> st; 6 int score = 0; 7 for (const char c : s) { 8 if (c == '(') 9 st.push(score), score = 0; 10 else { 11 score = score ? 2 * score : 1; 12 score += st.top(); 13 st.pop(); 14 } 15 } 16 return score; 17 } 18 }; 19 20 // O(1) memory solution 21 class Solution { 22 public: 23 int scoreOfParentheses(const string &s) { 24 int res = 0, l = 0; 25 for (int i = 0; i < s.size(); i++) { 26 l += s[i] == '(' ? 1 : -1; 27 if (s[i] == ')' && s[i - 1] == '(') res += 1 << l; 28 } 29 return res; 30 } 31 };