---
# System prepended metadata

title: 856. Score of Parentheses
tags: [Stack]

---

---
title: 856. Score of Parentheses
tags: Stack
description: share source code.
---

# 856. Score of Parentheses

```java

// used Stack to find (  and ) 
class Solution {
    public int scoreOfParentheses(String s) {
        Stack<Character> sk = new Stack<>();
        
        for(char c : s.toCharArray()){
            // if find ), I get all the number before )  
            if(c == ')'){
              int num = 0;  
              while(!sk.isEmpty() && sk.peek() !='('){
                 num += (sk.pop() -'0');
              } 
              sk.pop(); // (
              if(num == 0){ // if there is a case (), no num before ( set it to 1
                  num = 1;
              } else{
                  num *= 2;
              } 
              // (( () ))  -> stack (( 1 -> (2 -> 4 
              sk.push( (char) (num + '0') ); 
                
            }else{
                sk.push(c);
             
            }  
        }
        
        int output = 0;
        while(!sk.isEmpty()){
            output += (sk.pop() - '0');
        }
      
        return output;
    }
}
```