[Leetcode Learning-c++&java]Score of Parentheses(Score of Parentheses)

problem:

Difficulty: medium

Description:

Given a character array with only "(" and ")", then the rule is:

1. If two characters are consecutive "(" ")" [that is, "()"], 1 point is counted

2. Then if it contains "(())", then the score is 1 * 2, if it is "((()))", it is 1 * 2 * 2, and the parenthesis contains the inner parenthesis and the inner score is * 2

3. If it is ()(), add 1 + 1 adjacent direct fractions

Subject link: https://leetcode.com/problems/score-of-parentheses/submissions/

Input range:

  1. S is a balanced parentheses string, containing only ( and ).
  2. 2 <= S.length <= 50
  3. 题目一定会返回有匹配的括号组合不会突然出现只有 "(" 或者 ")" 得不到组合的数据

Enter the case:

Example 1:
Input: "()"
Output: 1

Example 2:
Input: "(())"
Output: 2

Example 3:
Input: "()()"
Output: 2

Example 4:
Input: "(()(()))"
Output: 6

My code:

At first glance, it feels that it is more appropriate to use stack processing. First, perform bracket matching, and find that it is adjacent to 1 point directly, and then if it is expanded, it is *2. This is the case, but writing code will be discussed separately.

You have to consider that this must match the parentheses from the inside, so after I match the parenthesis score and the parentheses together, I simply deal with it:

For example: ((())()) --> ((1)1) --> (21) --> (3) --> 6, feel it yourself

Java:

class Solution {
    public int scoreOfParentheses(String S) {
        char[] chs = S.toCharArray();
        int len = S.length(), top = -1;
        int[] stack = new int[len + 2 >> 1]; // 使用 栈 计分,长度只需要一半 + 1 就行
        for(int i = 0; i < len; i ++) {
            char ch = chs[i];
            if(ch == '(') stack[++ top] = -1;  // 如果是 ( 就直接标记为 -1,不直接加分
            else {
                if(stack[top] == -1) stack[top] = 1; // 如果 ( 直接遇到 ) 计 1 分,直接放到栈顶
                else {
                    int temp = 0;  // 如果不是就进行累加
                    while(top >= 0 && stack[top] != -1) temp += stack[top --];
                    stack[top] = temp << 1; // 放回栈顶
                }
            }
        }
        for(int i = 1; i <= top; i ++) stack[0] += stack[i]; // 最后累计
        return stack[0]; 
    }
}

C++:

class Solution {
public:
    int scoreOfParentheses(string S) {
        int len = S.size(), top = -1, *stack = new int[(len + 2) >> 1];
        for(int i = 0; i < len; i ++) {
            if(S[i] == '(') stack[++top] = -1;
            else {
                if(stack[top] == -1) stack[top] = 1;
                else {
                    int temp = 0;
                    while(top >= 0 && stack[top] != -1) temp += stack[top --];
                    stack[top] = temp << 1;
                }
            }
        }
        for(int i = 1; i <= top; i ++) stack[0] += stack[i];
        return stack[0];
    }
};

 

 

 

Guess you like

Origin blog.csdn.net/qq_28033719/article/details/114067287