LeetCode/String
[Medium] 856. Score of Parentheses
Developer07
2022. 9. 12. 11:53
#문제 설명
Leetcode 856번 문제는 괄호로 구성된 문자열이 구성된다. 이 괄호들 패턴에는 점수가 있다. () 는 1 점, ()() 는 1 + 1 = 2, (()) = 2 * 1 = 2 이다. 예를 들어 (()()) 라는 문자열이 주어지면 () + () = 2 이고 (2) 는 2 * 2 이기때문에 4가 정답이다.
#문제 풀이
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 {
score = st.pop() + Math.max(2 * score, 1);
}
}
return score;
}
}
이 문제는 스택을 사용하면 간단히 풀수있다.