[Programmers] 쇠막대기 - 스택/큐

동민·2021년 3월 11일
import java.util.LinkedList;
import java.util.Queue;

// 쇠막대기 - 스택/큐
public class IronStick { // 위 문제는 스택을 활용하는 문제임

	public int solution(String arrangement) {
		int answer = 0, stick = 0;

		Queue<String> queue = new LinkedList<>(); // Queue가 아닌 List로 구현해도 되지만 Queue일 때 실행속도가 훨씬 빠름

		for (int i = 1; i <= arrangement.length(); i++) {
			if (arrangement.charAt(i - 1) == '(' && arrangement.charAt(i) == ')') { // Short Circuit Evaluation 때문에 가능한 코드이다. 만약 ( arrangement.charAt(i) == ')' && arrangement.charAt(i - 1) == '(' ) 이 순서로 if문이 구현 됐다면 IndexOutofBoundsException이 발생할 것이다.
				queue.offer("()"); // 레이져는 묶어서 저장
				i++;
			} else {
				queue.offer(arrangement.charAt(i - 1) + "");
			}
		}
		while (!queue.isEmpty()) { // Queue가 아닌 List로 구현해도 되지만 Queue일 때 실행속도가 훨씬 빠름
			String ele = queue.poll(); // List.get(index) 보다 Queue.poll()이 더 빠름
			if (ele.equals("()")) {
				answer += stick;
			} else if (ele.equals("(")) {
				stick++;
			} else if (ele.equals(")")) {
				answer++;
				stick--;
			}
		}

		return answer;
	}

	public static void main(String[] args) {
		IronStick s = new IronStick();
		System.out.println(s.solution("()(((()())(())()))(())")); // 17
	}
}
profile
BE Developer

0개의 댓글