856:括号的分数

This commit is contained in:
huangge1199@hotmail.com 2021-04-25 23:20:38 +08:00
parent ef716fe114
commit dbf69d5616
3 changed files with 136 additions and 1 deletions

View File

@ -0,0 +1,92 @@
//给定一个平衡括号字符串 S按下述规则计算该字符串的分数
//
//
// () 1
// AB A + B 其中 A B 是平衡括号字符串
// (A) 2 * A 其中 A 是平衡括号字符串
//
//
//
//
// 示例 1
//
// 输入 "()"
//输出 1
//
//
// 示例 2
//
// 输入 "(())"
//输出 2
//
//
// 示例 3
//
// 输入 "()()"
//输出 2
//
//
// 示例 4
//
// 输入 "(()(()))"
//输出 6
//
//
//
//
// 提示
//
//
// S 是平衡括号字符串且只含有 ( )
// 2 <= S.length <= 50
//
// Related Topics 字符串
// 👍 204 👎 0
package leetcode.editor.cn;
import java.util.Stack;
//856:括号的分数
public class ScoreOfParentheses {
public static void main(String[] args) {
//测试代码
Solution solution = new ScoreOfParentheses().new Solution();
//1
System.out.println(solution.scoreOfParentheses("()"));
//2
System.out.println(solution.scoreOfParentheses("(())"));
//2
System.out.println(solution.scoreOfParentheses("()()"));
//6
System.out.println(solution.scoreOfParentheses("(()(()))"));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int scoreOfParentheses(String S) {
if (S == null) {
return 0;
}
int sum = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == '(') {
stack.push(0);
} else if (S.charAt(i) == ')') {
int num = stack.peek() == 0 ? 1 : stack.peek() * 2;
stack.pop();
if (stack.isEmpty()) {
sum += num;
} else {
stack.push(stack.pop()+num);
}
}
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,43 @@
<p>给定一个平衡括号字符串&nbsp;<code>S</code>,按下述规则计算该字符串的分数:</p>
<ul>
<li><code>()</code> 得 1 分。</li>
<li><code>AB</code>&nbsp;<code>A + B</code>&nbsp;分,其中 A 和 B 是平衡括号字符串。</li>
<li><code>(A)</code>&nbsp;<code>2 * A</code>&nbsp;分,其中 A 是平衡括号字符串。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<pre><strong>输入: </strong>&quot;()&quot;
<strong>输出: </strong>1
</pre>
<p><strong>示例 2</strong></p>
<pre><strong>输入: </strong>&quot;(())&quot;
<strong>输出: </strong>2
</pre>
<p><strong>示例&nbsp;3</strong></p>
<pre><strong>输入: </strong>&quot;()()&quot;
<strong>输出: </strong>2
</pre>
<p><strong>示例&nbsp;4</strong></p>
<pre><strong>输入: </strong>&quot;(()(()))&quot;
<strong>输出: </strong>6
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>S</code>&nbsp;是平衡括号字符串,且只含有&nbsp;<code>(</code>&nbsp;&nbsp;<code>)</code>&nbsp;</li>
<li><code>2 &lt;= S.length &lt;= 50</code></li>
</ol>
<div><div>Related Topics</div><div><li></li><li>字符串</li></div></div>\n<div><li>👍 204</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long