본문 바로가기

JAVA

JAVA(2022.09.08) - Stack,Queue를 활용하는 사고 기르기

  프로그래머스<올바른 괄호>라는 문제를 풀어보려 하였다. 이 문제는 Stack/Queue를 활용해야 하는 문제인데, 지금까지 Stack/Queue 카테고리의 문제들도  arrayList나 for문을 위주로 풀었기에, Stack/Queue가 활용된 코드를 review하는 시간을 가져보고자 한다. 

 

Stack : first in-Last Out, Last in-First Out

Queue : first in- first Out, Last in-Last Out

 

 

 

1. 배열에서 연속되는 숫자의 중복을 없애려면 ? 

 

import java.util.*;

public class Solution {
    public int[] solution(int []arr) {        
        Stack<Integer> stack = new Stack<>();
		//Stack생성 
        
        for (int n : arr) {
            if (stack.isEmpty() || stack.peek() != n) {
            //stack.isEmpty()는 배열에 처음 숫자를 넣으려고 하기 위해 필요
            //peek()!=n은 전에 들어간 숫자와 같지 않으면 stack에 넣어줌 
                stack.add(n);
            }
        }
        
        

        int[] answer = new int[stack.size()];
        int index = 0;
        for (int n : stack) {
            answer[index++] = n;
            //peek이나 pop을 사용하면 Stack 특성 상 Last in이 먼저 나오게 됨으로써 순서가 바뀜
 			//향상된 for문을 통해 Stack순서 그대로 구현시킴 
        }
        

        return answer;
    }
}

 

 

 

2. 탑 쌓기 

ex) [6,9,5,7,4]           > [0,0,2,2,4] 가 되도록

레이저는 왼쪽으로만 가능. 자기보다 높은 탑만 레이저 신호를 받을 수 있음. 몇번째(not index)탑이 레이저 신호를 받는지 

 

import java.util.Stack;

class Solution{
  public int[] solution(int[] heights){
    int[] answer = new int[heights.length];
    Stack<Integer> stack = new Stack<>();
    
    for(int height:heights{
      stack.push(height);
    }
    while(!stack.isEmpty()){
      int heiht = stack.pop();
      for(int i=stack.size(); i>=0; i--){
        if(height < heights[i]) {
          answer[stack.size()] = i+1;
          break;
        }
      }
    }
    return answer; 
  }
}

 

3. 스택 2개로 Queue 구현하기 

 

public class Queue {

	private Stack inBox = new Stack();
	private Stack outBox = new Stack();
	
	public void enQueue(Object item) {
		inBox.add(item);
	}
	
	public Object deQueue() {
		
		if (outBox.isEmpty()) {
			while(!inBox.isEmpty()) {
				outBox.push(inBox.pop());
			}
		}
		return outBox.pop();
	}
	
	public static void main(String[] args) {
		Queue queue = new Queue();
		queue.enQueue("A");
		queue.enQueue("B");
		queue.enQueue("C");
		
		System.out.println(queue.deQueue());
		System.out.println(queue.deQueue());
		System.out.println(queue.deQueue());
	}

}

출처: https://creatordev.tistory.com/83 [Creator Developer:티스토리]

 

 

이 외에도 여러 적용 예시들을 찾아보니 점점 적용할 수 있겠다는 생각이 든다. 

내일 더 알아보도록 하자