"(a)()" -> "(a)()". 1point 3acres 璁哄潧
"((bc)" -> "(bc)"
")))a((" -> "a"
"(a(b)" ->"(ab)" or "a(b)"
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(getValidString("((bc)"));
System.out.println(getValidString("(a)()"));
System.out.println(getValidString(")))a(("));
System.out.println(getValidString("(a(b)"));
}
static String getValidString(String str) {
int left = 0, right = 0;
Stack<Character> temp = new Stack<>();
Stack<Character> res = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(') {
left++;
temp.push(c);
} else if (c == ')') {
if (left > 0) {
left--;
temp.push(c);
}
} else {
temp.push(c);
}
}
while (!temp.isEmpty()) {
char t = temp.pop();
if (t == ')') {
right++;
res.push(t);
} else if (t == '(') {
if (right > 0) {
right--;
res.push(t);
}
} else {
res.push(t);
}
}
StringBuilder sb = new StringBuilder();
while (!res.isEmpty()) {
sb.append(res.pop());
}
return sb.toString();
}