publicstaticintscoreOfParentheses(String S){ int length = S.length(); int sum = 0; int n = 0; for (int i = 0; i < length; i++) { if (S.charAt(i) == '(') { if (n == 0) { n = 1; } else { n = n << 1; } } elseif (S.charAt(i) == ')') { if (S.charAt(i - 1) == '(') { sum += n; } n = n >> 1;
} } return sum; }
publicstaticintscoreOfParentheses2(String S){ Stack<Integer> stack = new Stack<>(); int length = S.length(); for (int i = 0; i < length; i++) { if (S.charAt(i) == '(') { stack.push(-1); } else { int temp = 0; while (!stack.isEmpty()) { Integer pop = stack.pop(); if (pop != -1) { temp += pop; continue; } else { if (temp == 0) stack.push(1); else stack.push(temp * 2); break; }
} } } int res = 0; while (!stack.empty()) { res += stack.pop(); } return res; } /* 时间复杂度:O(n) 空间复杂度:O(n) */ publicstaticintscoreOfParentheses3(String s){ Deque<Integer> st = new ArrayDeque<Integer>(); st.push(0); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { st.push(0); } else { int v = st.pop(); int top = st.pop() + Math.max(2 * v, 1); st.push(top); } } return st.peek(); }
publicstaticvoidmain(String[] args){ String s = "((((((())))()())))"; /* System.out.println(scoreOfParentheses(s)); System.out.println(scoreOfParentheses2(s));*/
classSolution{ publicintscoreOfParentheses(String s){ Deque<Character> deque = new ArrayDeque(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') deque.addLast('('); else { char c = deque.removeLast(); if (c == '(') { deque.addLast('1'); } else { int sum = c - '0'; while ((c = deque.removeLast()) != '(') sum += c - '0'; deque.addLast((char) ((sum << 1) + '0')); } } } int result = 0; while (!deque.isEmpty()) result += deque.removeLast() - '0'; return result; } }