Advertisement
pexea12

parentheses

Dec 25th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.    
  4.     int scoreOfParentheses(string S) {
  5.         stack<char> p;
  6.         stack<int> v;
  7.        
  8.         for (int i = 0; i < S.size(); ++i) {
  9.             if (S[i] == '(') {
  10.                 p.push('(');
  11.             } else {
  12.                 int total = 0;
  13.                 while (p.top() != '(') {
  14.                     total += v.top();
  15.                     p.pop();
  16.                     v.pop();
  17.                 }
  18.                
  19.                
  20.                 if (total > 0) {
  21.                     v.push(total * 2);
  22.                 } else {
  23.                     v.push(1);
  24.                 }
  25.                
  26.                 p.pop();
  27.                 p.push('*');
  28.             }
  29.         }
  30.        
  31.         int sum = 0;
  32.         while (!v.empty()) {
  33.             sum += v.top();
  34.             v.pop();
  35.         }
  36.        
  37.         return sum;
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement