본문으로 바로가기

Description

아래와 같이 소괄호로 이루어진 문자열이 주어졌을때 점수를 계산하여 반환하는 문제입니다. 괄호안에 있는 괄호가 있을경우 해당 괄호 수에 *2점을 추가점수로 얻을 수 있습니다.

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, where A and B are balanced parentheses strings.
  • (A) has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: s = "()"
Output: 1

Example 2:

Input: s = "(())"
Output: 2

Example 3:

Input: s = "()()"
Output: 2

Constraints:

  • 2 <= s.length <= 50
  • s consists of only '(' and ')'.
  • s is a balanced parentheses string.

Solution 1. Stack

public static int scoreOfParentheses(String s) {

    Stack<Integer> stack = new Stack<>();
    for(char c : s.toCharArray()){
        if (c == '(') {
            stack.push(-1);
        } else {
            int cur = 0;
            while (stack.peek() != -1) {
                cur += stack.pop();
            }
            stack.pop();
            stack.push(cur == 0 ? 1 : cur * 2);
        }
    }

    int score = 0;
    while (!stack.isEmpty()) {
        score += stack.pop();
    }
    return score;
}

스택을 이용하여 열린괄호를 -1로 표시해서 푸쉬하고 닫힌괄호를 만났을때 마지막 열린괄호가 있는 지점까지 위치를 계산하여 없으면 1점, 아니면 해당 거리*2만큼 점수를 계산해줍니다.

Reference

 

Score of Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com