LeetCode-856 Score of Parentheses Solution (with Java)

1. Description:

Notes:

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-05-09
 3  */
 4 class Solution {
 5     public int scoreOfParentheses(String S) {
 6         Stack<Integer> stack = new Stack<>();
 7         for (char c : S.toCharArray()) {
 8             if (c == '(') {
 9                 stack.push(-1);
10             } else {
11                 int cur = 0;
12                 while (stack.peek() != -1) {
13                     cur += stack.pop();
14                 }
15                 stack.pop();
16                 stack.push(cur == 0 ? 1 : cur * 2);
17             }
18         }
19         int sum = 0;
20         while (!stack.isEmpty()) {
21             sum += stack.pop();
22         }
23         return sum;
24     }
25 }

 

posted @ 2020-03-02 14:36  SheepCore  阅读(205)  评论(0编辑  收藏  举报