当前位置:网站首页>Stack Title: fractions in parentheses

Stack Title: fractions in parentheses

2022-06-24 10:32:00 The great Cherny

subject

Title and provenance

title : The fraction in brackets

Source :856. The fraction in brackets

difficulty

6 level

Title Description

requirement

Given a balanced bracket string s \texttt{s} s, Returns the fraction of a string .

The score of the balanced bracket string is calculated according to the following rules :

  • "()" \texttt{"()"} "()" have to 1 \texttt{1} 1 branch .
  • AB \texttt{AB} AB have to A + B \texttt{A} + \texttt{B} A+B branch , among A \texttt{A} A and B \texttt{B} B Is a balanced parenthesis string .
  • (A) \texttt{(A)} (A) have to 2 × A \texttt{2} \times \texttt{A} 2×A branch , among A \texttt{A} A Is a balanced parenthesis string .

Example

Example 1:

Input : s   =   "()" \texttt{s = "()"} s = "()"
Output : 1 \texttt{1} 1

Example 2:

Input : s   =   "(())" \texttt{s = "(())"} s = "(())"
Output : 2 \texttt{2} 2

Example 3:

Input : s   =   "()()" \texttt{s = "()()"} s = "()()"
Output : 2 \texttt{2} 2

Example 4:

Input : s   =   "(()(()))" \texttt{s = "(()(()))"} s = "(()(()))"
Output : 6 \texttt{6} 6

Data range

  • 2 ≤ s.length ≤ 50 \texttt{2} \le \texttt{s.length} \le \texttt{50} 2s.length50
  • s \texttt{s} s Contains only ‘(’ \texttt{`('} ‘(’ and ‘)’ \texttt{`)'} ‘)’
  • s \texttt{s} s Is a balanced parenthesis string

Solution 1

Ideas and algorithms

Due to the given string s s s Is a balanced parenthesis string , So every left parenthesis has a right parenthesis matching . According to the rules of score calculation , Scores are related to nesting levels and primitive scores . The meaning of the primitive is a non empty balanced string , It cannot be split into two balanced string splicing forms .

To calculate the fraction in parentheses , You can use the stack to store scores , Each time a closing bracket is encountered, the score is calculated according to the elements in the stack .

Traversing the string from left to right s s s, If you encounter an open parenthesis, you will 0 0 0 Push , When the right bracket is encountered , There may be two situations :

  1. The first character is an open parenthesis , At this point, the current closing bracket is “()" \text{``()"} “()" Part of , The score is 1 1 1;

  2. The previous character is a closing bracket , Then the previous right bracket has calculated the score and is put on the stack , At this time, the previous bracket is in the inner layer , The current closing parenthesis is in the outer layer , The effect of the outer bracket on the score is to multiply the sum of the scores of the inner bracket by 2 2 2.

In both cases, the following method can be used to calculate the score at the current right bracket : Take the elements in the stack out of the stack in turn , Until the element 0 0 0, Elements 0 0 0 Is the left bracket that matches the current right bracket ( Because the inner left parenthesis already matches the right parenthesis , So the inner left bracket corresponds to 0 0 0 All have been released ), Calculate the sum of stack elements score \textit{score} score, Then calculate the score at the current closing bracket . according to score \textit{score} score Value , The calculation methods are as follows :

  • If score = 0 \textit{score} = 0 score=0, Then it corresponds to the above situation 1, Therefore, the current score in the right bracket is 1 1 1;

  • If score > 0 \textit{score} > 0 score>0, Then it corresponds to the above situation 2, Therefore, the current score in the right bracket is score × 2 \textit{score} \times 2 score×2.

After calculating the score at the current closing bracket , Put the score on the stack .

After the traversal , The elements in the stack are strings s s s The fraction of each primitive in , Calculate the sum of the elements in the stack , String s s s The scores of .

Consider the following parenthesized string : s = “()(()(()))" s = \text{``()(()(()))"} s=“()(()(()))". The length of the string is 10 10 10, The process of calculating the score is as follows .

Subscript 0 0 0: The character is ‘(’ \text{`('} ‘(’, take 0 0 0 Push , Now the stack is [ 0 ] [0] [0], The left side is the bottom of the stack , On the right is the top of the stack .

Subscript 1 1 1: The character is ‘)’ \text{`)'} ‘)’, take 0 0 0 Out of the stack , take 1 1 1 Push , Now the stack is [ 1 ] [1] [1].

Subscript 2 2 2: The character is ‘(’ \text{`('} ‘(’, take 0 0 0 Push , Now the stack is [ 1 , 0 ] [1, 0] [1,0].

Subscript 3 3 3: The character is ‘(’ \text{`('} ‘(’, take 0 0 0 Push , Now the stack is [ 1 , 0 , 0 ] [1, 0, 0] [1,0,0].

Subscript 4 4 4: The character is ‘)’ \text{`)'} ‘)’, take 0 0 0 Out of the stack , take 1 1 1 Push , Now the stack is [ 1 , 0 , 1 ] [1, 0, 1] [1,0,1].

Subscript 5 5 5: The character is ‘(’ \text{`('} ‘(’, take 0 0 0 Push , Now the stack is [ 1 , 0 , 1 , 0 ] [1, 0, 1, 0] [1,0,1,0].

Subscript 6 6 6: The character is ‘(’ \text{`('} ‘(’, take 0 0 0 Push , Now the stack is [ 1 , 0 , 1 , 0 , 0 ] [1, 0, 1, 0, 0] [1,0,1,0,0].

Subscript 7 7 7: The character is ‘)’ \text{`)'} ‘)’, take 0 0 0 Out of the stack , take 1 1 1 Push , Now the stack is [ 1 , 0 , 1 , 0 , 1 ] [1, 0, 1, 0, 1] [1,0,1,0,1].

Subscript 8 8 8: The character is ‘)’ \text{`)'} ‘)’, take 1 1 1 Out of the stack , And then 0 0 0 Out of the stack , take 2 2 2 Push ( 2 = 1 × 2 2 = 1 \times 2 2=1×2), Now the stack is [ 1 , 0 , 1 , 2 ] [1, 0, 1, 2] [1,0,1,2].

Subscript 9 9 9: The character is ‘)’ \text{`)'} ‘)’, take 2 2 2 1 1 1 Out of the stack , And then 0 0 0 Out of the stack , take 6 6 6 Push ( 6 = ( 2 + 1 ) × 2 6 = (2 + 1) \times 2 6=(2+1)×2), Now the stack is [ 1 , 6 ] [1, 6] [1,6].

End of traversal , The sum of the elements in the stack is 7 7 7, For the string s s s The scores of .

Code

class Solution {
    
    public int scoreOfParentheses(String s) {
    
        Deque<Integer> stack = new ArrayDeque<Integer>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
    
            if (s.charAt(i) == '(') {
    
                stack.push(0);
            } else {
    
                int score = 0;
                while (stack.peek() != 0) {
    
                    score += stack.pop();
                }
                stack.pop();
                int newScore = score == 0 ? 1 : score * 2;
                stack.push(newScore);
            }
        }
        int totalScore = 0;
        while (!stack.isEmpty()) {
    
            totalScore += stack.pop();
        }
        return totalScore;
    }
}

Complexity analysis

  • Time complexity : O ( n ) O(n) O(n), among n n n Is string s s s The length of . Need to traverse the string s s s once , The scores corresponding to each subscript are put on and out of the stack once respectively .

  • Spatial complexity : O ( n ) O(n) O(n), among n n n Is string s s s The length of . The space complexity mainly depends on the stack space .

Solution 2

Ideas and algorithms

According to the rules of score calculation , “()" \text{``()"} “()" My score is 1 1 1, In the case of string splicing, the scores are calculated for each primitive , In the case of nested brackets, the score is calculated according to the number of nested levels .

For string splicing , Just calculate the score for each primitive , Don't need special treatment .

For the case of nested parentheses , Only “()" \text{``()"} “()"( A continuous pair of left and right parentheses ) Will contribute to the score , The score is determined by the number of layers . Definition “()" \text{``()"} “()" The number of layers of is the number of unmatched left parentheses on the left or the number of unmatched right parentheses on the right , for example “()(()(()))" \text{``()(()(()))"} “()(()(()))" There are three pairs “()" \text{``()"} “()", Each pair from left to right “()" \text{``()"} “()" The depth of is 0 0 0 1 1 1 2 2 2. When “()" \text{``()"} “()" The number of layers is level \textit{level} level when , Its contribution to the score is 2 level 2^\textit{level} 2level.

The following solution can be obtained : Number of layers level \textit{level} level Initialize to 0 0 0, Traversing the string from left to right s s s, encounter ‘(’ \text{`('} ‘(’ Will level \textit{level} level Add 1 1 1, encounter ‘)’ \text{`)'} ‘)’ Will level \textit{level} level reduce 1 1 1, When you meet “()" \text{``()"} “()" when , take 2 level 2^\textit{level} 2level Add to the score , After traversal, you can get the string s s s The scores of .

Code

class Solution {
    
    public int scoreOfParentheses(String s) {
    
        int score = 0, level = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
    
            if (s.charAt(i) == '(') {
    
                level++;
            } else {
    
                level--;
                if (s.charAt(i - 1) == '(') {
    
                    score += 1 << level;
                }
            }
        }
        return score;
    }
}

Complexity analysis

  • Time complexity : O ( n ) O(n) O(n), among n n n Is string s s s The length of . Need to traverse the string s s s once , The calculation time at each subscript is O ( 1 ) O(1) O(1).

  • Spatial complexity : O ( 1 ) O(1) O(1).

原网站

版权声明
本文为[The great Cherny]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240926213798.html