leet-code/src/main/java/leetcode/editor/cn/RemoveOutermostParentheses.java
2021-04-29 23:21:52 +08:00

79 lines
2.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//有效括号字符串为空 ("")、"(" + A + ")" 或 A + B其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"""()"
//"(())()" 和 "(()(()))" 都是有效的括号字符串。
//
// 如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法我们称其为原语primitive其中 A 和 B 都是非空有效括号字符串。
//
// 给出一个非空有效字符串 S考虑将其进行原语化分解使得S = P_1 + P_2 + ... + P_k其中 P_i 是有效括号字符串原语。
//
// 对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。
//
//
//
// 示例 1
//
// 输入:"(()())(())"
//输出:"()()()"
//解释:
//输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())"
//删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
//
// 示例 2
//
// 输入:"(()())(())(()(()))"
//输出:"()()()()(())"
//解释:
//输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))"
//删除每个部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
//
//
// 示例 3
//
// 输入:"()()"
//输出:""
//解释:
//输入字符串为 "()()",原语化分解得到 "()" + "()"
//删除每个部分中的最外层括号后得到 "" + "" = ""。
//
//
//
//
// 提示:
//
//
// S.length <= 10000
// S[i] 为 "(" 或 ")"
// S 是一个有效括号字符串
//
// Related Topics 栈
// 👍 163 👎 0
package leetcode.editor.cn;
//1021:删除最外层的括号
public class RemoveOutermostParentheses {
public static void main(String[] args) {
//测试代码
Solution solution = new RemoveOutermostParentheses().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String removeOuterParentheses(String S) {
int count = 0;
String result = "";
for (char ch : S.toCharArray()) {
if (ch == '(') {
count++;
result = count > 1 ? result + ch : result;
}else{
count--;
result = count > 0 ? result + ch : result;
}
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}