LeetCode 1021. Remove Outermost Parentheses (删除最外层的括号)
题目标签:Stack
设置 opened, 遇到 ( opened++, 遇到 ) opened--;
为了移除最外面一层的括号, 设置为 当 opened 大于 0 的时候, 存入左括号;当 opened 大于 1 的时候,存入 右括号。
具体看code。
Java Solution:
Runtime: 2 ms, faster than 97.83%
Memory Usage: 38.4 MB, less than 5.19%
完成日期:02/15/2020
关键点:stack
class Solution { public String removeOuterParentheses(String S) { StringBuilder s = new StringBuilder(); int opened = 0; for(char c : S.toCharArray()) { if(c == '(') { if(opened > 0) s.append(c); opened++; } if(c == ')') { if(opened > 1) s.append(c); opened--; } } return s.toString(); } }
参考资料:LeetCode Discuss
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/