https://www.acmicpc.net/problem/10799
이번 문제는 스택에 관한 문제이다.(기본적으로 괄호 문제들은 스택과 연관되어있음)
이 문제가 조금 까다로운 이유는 문제 해석일 것이다.
문제에서 () = 무조건 레이저이고, 레이저는 생성되면 사라지지 않기 때문에 스택에 남아있어야 한다.
따라서 레이저의 개수를 스택에 담는 것이 키포인트가 된다.
따라서 3가지 과정을 이용해 설계해야 하며, 과정은 다음과 같다.
1. peek가 ( 이고 다음 들어갈 문자가 ) 일 경우 => 레이저이기 때문에 레이저 개수인 1을 스택에 넣는다.
2. peek가 숫자 이고 다음 들어갈 문자가 ) 일 경우 => 레이저가 막대기를 잘라야 하는 시점이기 때문에 peek가 숫자가 아닐때 까지 pop을 해주고(레이저 개수를 세는것) peek가 ( 일때 막대기를 잘라준다.(레이저 개수+1개)
3. 다음 들어갈 문자가 ( 일 경우 => 스택에 ( 를 넣어줌.
import java.util.*; class Main { public static void main(String argv[]) { Scanner sc = new Scanner(System.in); String stick = sc.next(); Stack<String> st = new Stack<>(); int count = 0; int answer = 0; for(int i=0;i<stick.length();i++){ if(st.empty()){ st.push(String.valueOf(stick.charAt(i))); } else{ if(st.peek().equals("(")&&stick.charAt(i)==')'){ st.pop(); st.push("1"); } else if(Character.isDigit(st.peek().charAt(0))&&stick.charAt(i)==')'){ while(Character.isDigit(st.peek().charAt(0))){ count+=Integer.valueOf(st.pop()); } if(st.peek().equals("(")){ st.pop(); st.push(Integer.toString(count)); answer+=count+1; count=0; } } else if(stick.charAt(i)=='('){ st.push("("); } } } System.out.print(answer); } }