1021. 删除最外层的括号1021. 删除最外层的括号
1. 题目
题目链接
2. 题目分析
题目这么长,意思就是将每一组的括号的最外层一对括号去除,保存里面的括号组成新的字符串。
3. 解题思路
-
方法一:
- 像这种括号匹配,如果写过计算器功能的算法,就知道需要使用栈来匹配每一对括号。遍历括号字符串S时,用startIndex记录每一组原语的第一个"("的下标,用endIndex记录原语的最后一个“)”,然后通过S.substring(startIndex+1, endIndex)即这个原语去掉最外层括号后的字符串。当遇到左括号就入栈,当遇到右括号,就把一个左括号弹出栈;当栈空的时候,就说明找到了一个原语。
-
方法二:
- 一对原语的左括号数量会等于右括号数量,所以可以遍历字符串,然后统计左右括号的数量left、right,当left != right时,说明左右括号不相等,所以当前遍历属于在原语里面,则可以记录这个符号;当left == right时,说明已经找到一组原语;注意,每次遍历时,从原语的第二符号开始(因为第一个符号一定是"(" ),这也是left初始值为1的原因,而right=0。
4. 代码实现(java)
package com.algorithm.leetcode.string;
import java.util.Stack;
/**
* Created by 凌 on 2019/8/3.
* 注释:
*/
public class RemoveOuterParentheses {
public static void main(String[] args) {
// String S = "(()())(())";
String S = "()";
String result = removeOuterParentheses(S);
System.out.println(result);
String result_1 = removeOuterParentheses_1(S);
System.out.println(result_1);
}
public static String removeOuterParentheses(String S) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < S.length(); i++) {
if (stack.isEmpty() && S.charAt(i) == '('){
stack.push(S.charAt(i));
startIndex = i;
}else{
if (S.charAt(i) == ')' && stack.peek() == '('){
if (stack.size() == 1){
endIndex = i;
stack.pop();
result.append(S.substring(startIndex+1, endIndex));
}else{
stack.pop();
}
}else{
stack.push(S.charAt(i));
}
}
}
return result.toString();
}
public static String removeOuterParentheses_1(String S) {
StringBuilder sb = new StringBuilder();
int left = 1;
int right = 0;
char[] chs = S.toCharArray();
for (int i = 1; i < chs.length; i++) {
if (chs[i] == '('){
left++;
}else{
right++;
}
if (left == right){
left = 1;
right = 0;
i++;
}else{
sb.append(chs[i]);
}
}
return sb.toString();
}
}