ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 04. Stack
    멋사 부트캠프/자료구조 2025. 5. 4. 14:07

    1. Stack 이란?

     

    2. Stack의 활용(with Java)

        * isEmpty() : 배열이 비어 있는지 확인 (top == -1 인지 조건검사)

        * isFull() : 배열이 꽉차 있는지 확인 (top == length-1 인지 조건검사) 

        * peek() : 현재 위치(맨위)의 데이터를 조회만 함. 

        * pop() : 현재 위치(맨위)의 데이터를 조회한 후 리턴하고 삭제하며, top을 한칸 내린다.

        * push() : 현재 스택이 꽉차 있는지 검사한 후, 아니라면 top을 한칸 올리고 해당 내용을 추가한다.

    import java.util.Stack;
    
    public class StackWithJava {
    
    	public static void main(String[] args) {
    		String str1 = "(MyNames Jaybee)";
    		String str2 = "[MyNames Jaybee)";
    		String str3 = "Jaybee is back)";
    		String str4 = "(Jaybee is back";
    		String str5 = "Jaybee is back";
    		
    		System.out.println(isValid(str1));
    		System.out.println(isValid(str2));
    		System.out.println(isValid(str3));
    		System.out.println(isValid(str4));
    		System.out.println(isValid(str5));
    	
    	}
    	
    	public static boolean isValid(String str) {
    		Stack<Character> st = new Stack<>();
    		
    		for(char ch : str.toCharArray()) {
    			if(ch == '(') st.push(')');
    			else if(ch == '{') st.push('}');
    			else if(ch == '[') st.push(']');
    			else if(ch != ')' && ch != ']' && ch != '}') continue;
    			else if(st.isEmpty() || st.pop() != ch) return false;
    		}
    		return st.isEmpty();
    	}
    }

     

    활용되는 주요 알고리즘

    -> DFS (재귀를 사용함)

    '멋사 부트캠프 > 자료구조' 카테고리의 다른 글

    07. 그래프(Graph)  (0) 2025.05.15
    05. 큐(Queue)  (0) 2025.05.15
    03. 연결리스트  (1) 2025.04.17
    02. Array 활용  (0) 2025.03.19
    01. 자료구조 요약 정리  (0) 2025.03.19
Designed by Tistory.