Stack solution:
class Solution { public int scoreOfParentheses(String s) { Stack<Integer> st = new Stack<>(); int score = 0; for(int i = 0; i < s.length(); i++){ char ch = s.charAt(i); if(ch == '('){ st.push(score); score = 0; } else { if(score==0) score = 1; else score = 2*score; score += st.pop(); } } return score; } }
Recursive solution:
class Solution { int index = 0; public int scoreOfParentheses(String s) { int score = 0; while(index<s.length()){ char ch = s.charAt(index++); if(ch == '('){ score += scoreOfParentheses(s); } else { if(score==0) score = 1; else score = 2*score; return score; } } return score; } }