공부/알고리즘

스택(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;
			}
	}
}