File tree Expand file tree Collapse file tree 1 file changed +12
-22
lines changed Expand file tree Collapse file tree 1 file changed +12
-22
lines changed Original file line number Diff line number Diff line change 11class Solution {
2- public static int scoreOfParentheses (String S ) {
3- Stack <String > st = new Stack <>();
4- for (int i =0 ; i <S .length (); i ++) {
5- if (S .charAt (i ) == '(' ) {
6- st .push (String .valueOf (S .charAt (i )));
7- }
8- else {
9- int num = 0 ;
10- while (!st .peek ().equals ("(" )) {
11- num += Integer .parseInt (st .pop ());
12- }
13- st .pop ();
14- st .push (num == 0 ? String .valueOf ("1" ) : String .valueOf (2 *num ));
15- }
16- }
17-
18- int ans = 0 ;
19- while (!st .empty ()) {
20- ans += Integer .parseInt (st .pop ());
21- }
22-
23- return ans ;
2+ public int scoreOfParentheses (String S ) {
3+ Stack <Integer > stack = new Stack <>();
4+ int currMultiplier = 0 ;
5+ for (char c : S .toCharArray ()) {
6+ if (c == '(' ) {
7+ stack .push (currMultiplier );
8+ currMultiplier = 0 ;
9+ } else {
10+ currMultiplier = stack .pop () + Math .max (2 * currMultiplier , 1 );
11+ }
2412 }
13+ return currMultiplier ;
14+ }
2515}
You can’t perform that action at this time.
0 commit comments