tygarian

score of parentheses stack solution leetcode

Mar 17th, 2022
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. class Solution {
  2. public:
  3. // Time Complexity:- O(N)
  4. // Space Complexity:- O(N)
  5. int scoreOfParentheses(string s) {
  6. stack<int> st;
  7. for(auto& c:s){
  8. if(c=='('){
  9. st.push(-1);
  10. }
  11. else{
  12. int val = 0;
  13. while(st.top()!=-1){
  14. val += st.top();
  15. st.pop();
  16. }
  17. st.pop();
  18. if(val){
  19. st.push(val*2);
  20. }
  21. else{
  22. st.push(1);
  23. }
  24. }
  25. }
  26. int ans = 0;
  27. while(!st.empty() and st.top()!=-1){
  28. ans += st.top();
  29. st.pop();
  30. }
  31. return ans;
  32. }
  33. };
Add Comment
Please, Sign In to add comment