当前位置:网站首页>Stack Title: fractions in parentheses
Stack Title: fractions in parentheses
2022-06-24 10:32:00 【The great Cherny】
List of articles
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} 2≤s.length≤50
- 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 :
The first character is an open parenthesis , At this point, the current closing bracket is “()" \text{``()"} “()" Part of , The score is 1 1 1;
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).
边栏推荐
猜你喜欢
Resolved: methods with the same name as their class will not be constructors in
Flink cluster construction and enterprise level yarn cluster construction
2022 the most complete and detailed JMeter interface test tutorial and detailed interface test process in the whole network - JMeter test plan component (thread < user >)
3.员工的增删改查
Sort out interface performance optimization skills and kill slow code
26.删除有序数组的重复项
What you must know about distributed systems -cap
numpy. linspace()
Record the range of data that MySQL update will lock
Baidu online disk download has been in the process of requesting solutions
随机推荐
Six states of threads
【数据分析数据源】全国各省市行政区坐标(包含边界坐标点和中心坐标点)
抓包工具charles实践分享
机械臂速成小指南(一):机械臂发展概况
International Symposium on energy and environmental engineering in 2022 (coeee 2022)
The difference between static link library and dynamic link library
Machine learning perceptron and k-nearest neighbor
leetCode-1823: 找出游戏的获胜者
np. float32()
Leetcode-1051: height checker
Hill sorting graphic explanation + code implementation
26.删除有序数组的重复项
Leetcode - 498: traversée diagonale
How can I solve the problem that the swiper animation animation fails when switching between left and right rotations of the swiper?
【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)
Illustration miscellaneous [for archiving to prevent loss]
leetCode-面试题 01.05: 一次编辑
Leetcode-1823: find the winner of the game
uniapp实现点击拨打电话功能
[EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)