알고리즘/스택, 큐
[백준] 4889번 안정적인 문자열 #Java
VIPeveloper
2022. 6. 21. 13:54
728x90
반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int idx = 1;
while (true) {
String s = br.readLine();
if(s.startsWith("-")) break;
System.out.printf("%d. %d\n",idx, solution(s));
idx++;
}
}
private static int solution(String s) {
int cnt = 0;
char[] chars = s.toCharArray();
Stack<Character> st = new Stack<>();
for (int i = 0; i < chars.length; i++) {
if(chars[i] == '{'){
st.push(chars[i]);
}else{
if(st.isEmpty()){
cnt++;
st.push('{');
}else{
st.pop();
}
}
}
// 나머지는 다 { 밖에 없을 것이기 때문에 나누기 2 해준 것을 더한다.
cnt+=(st.size()/2);
return cnt;
}
}
728x90
반응형