Algorithm/leetcode
[leetcode] 856.Score of Parentheses(Retry)
세류오
2023. 8. 20. 22:11
https://leetcode.com/problems/score-of-parentheses/description/
Score of Parentheses - LeetCode
Can you solve this real interview question? Score of Parentheses - Given a balanced parentheses string s, return the score of the string. The score of a balanced parentheses string is based on the following rule: * "()" has score 1. * AB has score A + B, w
leetcode.com
설명
String s 를 매개변수로 받고, socre를 반환한다
score는 한쌍을 이루는 괄호(=> '()')의 점수체크를 하고 아래의 규칙을 따른다
- "()의 score 는 1 이다
- 한쌍을 이루는 괄호 A와 B에서 AB의 score는 A+B이다
-> "()()" = 1+1
- (A)는 2*A score를 가진다
-> "(()) = 2*1
풀이
"다시 풀어 볼 것"
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;
}
}