[백준] 4949번: 균형잡힌 세상

앙이🐯·2022년 1월 3일
0

알고리즘

목록 보기
9/22

백준 4949번: 균형잡힌 세상

1. 문제 설명

  • 예제 입력:

    So when I die (the [first] I will see in (heaven) is a score list).
    [ first in ] ( first out ).
    Half Moon tonight (At least it is better than no Moon at all].
    A rope may form )( a trail in a maze.
    Help( I[m being held prisoner in a fortune cookie factory)].
    ([ (([( [ ] ) ( ) (( ))] )) ]).
    .
    .

  • 예제 출력:

    yes
    yes
    no
    no
    no
    yes
    yes

2. 문제 풀이

스택(Stack): 후입선출(Last In First Out)로 pop()수행시 나중에 push()된 데이터가 먼저 나온다.

  • "."이 나오기 전까지 입력 받는다.
while(true) {
	s=sc.nextLine();
			
	if(s.equals(".")) {
		break;
	}			
}
  • 문자열을 한글자씩 문자로 바꾸어 괄호인지 판단 후 여는 괄호인지 닫는 괄호인지 판단
  • 여는 괄호일때 stack에 push
if(c=='('||c=='[') {
	stack.push(c);
}
  • 닫는 괄호일때 여는 괄호와 짝이 이루어져야함
  • 닫는 괄호일때 빈 스택이거나 여는 괄호와 짝이 이루어지지 않을 경우 "no"를 리턴
if(stack.isEmpty()||stack.peek()!='(') {
	return "no";
}
else {
	stack.pop();
}

if(stack.isEmpty()||stack.peek()!='[') {
	return "no";
}
else {
	stack.pop();
}
코드
import java.util.*;

public class No_4949 {
	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		String s="";
		
		while(true) {
			s=sc.nextLine();
			
			if(s.equals(".")) {
				break;
			}
			
			System.out.println(solution(s));
		}
		
	}
	
	public static String solution(String s) {

		
		Stack<Character> stack =new Stack<>();
		
		for(int i=0;i<s.length();i++) {
			char c=s.charAt(i);
			
			if(c=='('||c=='[') {
				stack.push(c);
			}
			else if(c==')') {
				if(stack.isEmpty()||stack.peek()!='(') {
					return "no";
				}
				else {
					stack.pop();
				}
			}
			else if(c==']') {
				if(stack.isEmpty()||stack.peek()!='[') {
					return "no";
				}
				else {
					stack.pop();
				}
			}
		}
		if(stack.isEmpty()) {
			return "yes";
		}
		else {
			return "no";
		}
		
	}

}
실행 결과

0개의 댓글