ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스택(stack)
    알고리즘 2023. 12. 2. 17:13

    S = (({[]}()[[]]))이 올바른 괄호쌍으로 이루어져 있는지 확인

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Stack;
    import java.util.StringTokenizer;
    
    public class Main {
    
    	public static void main(String[] args) throws IOException{
    	       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	       StringTokenizer st = new StringTokenizer(br.readLine());
    
    	       String str = st.nextToken();
    	      
    	       String[] S = str.split("");
    
    	       Stack<String> stack = new Stack<>();
    			
    			for(int i=0; i<S.length; i++){
    	
    			      if(S[i].equals("(")){
    	
    			            stack.push(")");
    	
    			      }else if(S[i].equals("{")){
    	
    			            stack.push("}");
    	
    			      }else if(S[i].equals("[")){
    	
    			            stack.push("]");
    	
    			      }else if(stack.size()==0 || !stack.pop().equals( S[i] )){
    			            System.out.println(false);
    			            return;
    			      }
    			}
    			if(stack.size()==0) {
    				System.out.println(true);
    				return;
    			}
    	}
    }

    '알고리즘' 카테고리의 다른 글

    재귀  (1) 2023.12.03
    Dictionary - 가장 긴 연속된 수열  (4) 2023.12.03
    딕셔너리  (2) 2023.12.03
    LIFO - java  (1) 2023.12.02
    Two Pointer  (2) 2023.12.02
Designed by Tistory.