SpecialChar(bool isLeft, int val = 0): isLeft(isLeft), val(val) {}; };
classSolution { public: intscoreOfParentheses(string& s){ stack<SpecialChar> st; for (char& c : s) { if (c == '(') { st.push(SpecialChar(true)); } else { // 必有左括号 int s = 0; while (!st.top().isLeft) { s += st.top().val; st.pop(); } st.pop(); // 对应左括号出栈 st.push(SpecialChar(false, s ? s * 2 : 1)); } } int ans = 0; while (st.size()) { ans += st.top().val; st.pop(); } return ans; } };
/* * @LastEditTime: 2026-10-05 16:39:47 */ classSolution { public: intscoreOfParentheses(const string& s){ int ans = 0; for (int i = 0, n = s.size(), layer = 0; i < n; i++) { if (s[i] == '(') { layer++; } else { layer--; if (s[i - 1] == '(') { ans += 1 << layer; } } } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
''' LastEditTime: 2026-10-05 16:45:23 ''' classSolution: defscoreOfParentheses(self, s: str) -> int: ans = layer = 0 for i, c inenumerate(s): if c == '(': layer += 1 else: layer -= 1 if s[i - 1] == '(': ans += 1 << layer return ans
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* * @LastEditTime: 2026-10-05 16:44:16 */ classSolution { publicintscoreOfParentheses(String s) { intans=0; for (inti=0, n = s.length(), layer = 0; i < n; i++) { if (s.charAt(i) == '(') { layer++; } else { layer--; if (s.charAt(i - 1) == '(') { ans += 1 << layer; } } } return ans; } }
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* * @LastEditTime: 2026-10-05 16:42:41 */ funcscoreOfParentheses(s string) (ans int) { layer := 0 for i, c := range s { if c == '(' { layer++ } else { layer-- if s[i - 1] == '(' { ans += 1 << layer } } } return }