여는 괄호와 닫는 괄호만으로 이루어진 문자열이 주어진다. 여기서 안정적인 문자열을 만들기 위한 최소 연산의 수를 구하려고 한다. 안정적인 문자열의 정의란 다음과 같다.
1. 빈 문자열은 안정적이다.
2. S가 안정적이라면, {S}도 안정적인 문자열이다.
3. S와 T가 안정적이라면, ST(두 문자열의 연결)도 안정적이다.
{}, {}{}, {{}{}}는 안정적인 문자열이지만, }{, {{}{, {}{는 안정적인 문자열이 아니다.
문자열에 행할 수 있는 연산은 여는 괄호를 닫는 괄호로 바꾸거나, 닫는 괄호를 여는 괄호로 바꾸는 것 2가지이다.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp = br.readLine();
int number = 1;
while (test(temp)) {
Stack<String> stack1 = new Stack<>();
int count = 0;
for (int i = 0; i < temp.length(); i++) {
if (stack1.isEmpty() && temp.charAt(i) == '}') {
count++;
stack1.push("{");
} else if (stack1.contains("{") && temp.charAt(i) == '}') {
stack1.pop();
} else {
stack1.push("{");
}
}
count += stack1.size() / 2;
System.out.println(number + ". " + count);
number++;
temp = br.readLine();
}
}
static boolean test (String input) {
return !input.contains("-");
}
}