package com.leetcode;
/**
* L-1021
* @author raymond
*
*/
public class RemoveOuterParentheses {
public static void main(String[] args) {
String s1 = "(()())(())(()(()))";
String result1 = removeOuterParentheses(s1);
System.out.println(result1);
/*String s2 = "()()";
String result2 = removeOuterParentheses(s2);
System.out.println(result2);
String s3 = "(()())(())";
String result3 = removeOuterParentheses(s3);
System.out.println(result3);*/
}
/**
* 思路:
* @param S
* @return
*/
public static String removeOuterParentheses(String S) {
char[] inArr = S.toCharArray(); // "(()())(())(()(()))" 字符串转字符数组
char[] resultArr = new char[inArr.length];
int bracesCnt = 0;
int outIncr = 0;
for (int i = 0; i < inArr.length ; i++) {
if (inArr[i] == ')') {
bracesCnt--; //每遍历至最外面一个')', bracesCnt都会减至0, 然后从最后面一个'(', bracesCnt重新开始自增
if(bracesCnt != 0){
resultArr[outIncr++] = ')';
}
} else {
if (bracesCnt != 0) {
resultArr[outIncr++] = '(';
}
bracesCnt++; //第一个'('不存入resultArr数组
}
//System.out.println(bracesCnt + "------" + outIncr);
}
return new String(resultArr).substring(0, outIncr);
}
}