18. Score of Parentheses
Input: "()"
Output: 1Input: "(())"
Output: 2Input: "()()"
Output: 2Input: "(()(()))"
Output: 6Solution: (Stack)
class Solution
{
public:
int scoreOfParentheses(string s)
{
stack<int> st;
st.push(0);
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(')
{
st.push(0);
}
else
{
int v = st.top();
st.pop();
int c = st.top();
st.pop();
c += max(1, 2 * v);
st.push(c);
}
}
return st.top();
}
};Last updated