[C++] 백준 - 7585번

SMongS·2023년 5월 29일
0

CodingTest

목록 보기
49/49

Brackets

문제

As a C/Java programmer, you will be used to dealing with brackets. For the purpose of this problem, we will consider three type of bracket, round (), square [] and curly {}. As you know, every opening bracket must have a corresponding closing bracket, and brackets must be correctly nested.

This problem will give you some pieces of code. You have to check whether the brackets are legal or not. To keep things simple, there will be no brackets enclosed in quotes (which do not follow the standard rules, of course). New line characters have also been removed, so each line of input represents one piece of code to be checked.

입력

Input will consist of a number of lines of text (code), each one containing no more than 250 characters. The last line of input will contain just # - this line should be ignored. Each piece of code must be checked for legal brackets, and its status reported.

출력

If a line of code contains no brackets, or if all brackets are correctly paired and nested, the output should be Legal on a line on its own. If there are any errors, the output should be Illegal on a line on its own.

예제 입력 1

void test(int num) { num = double(num); }
int count(int value) { return (value + 2; }
while(sum < 200) { sum += data[test(sum]); }
#

예제 출력 1

Legal
Illegal
Illegal

코드

#include <iostream>
#include <stack>

using namespace std;

int main(void) {
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	
	string str;
	while(getline(cin, str)){
		if(str == "#"){
			break;
		}
		
		bool check = false;
		stack<char> stk;		
		for(char c : str){
			if(c == '(' || c == '[' || c == '{'){
				stk.push(c);
			}
			else if(c == ')'){
				if(stk.top() == '('){
					stk.pop();
				}
				else{
					check = true;
					break;
				}
			}
			else if(c == ']'){
				if(stk.top() == '['){
					stk.pop();
				}
				else{
					check = true;
					break;
				}
			}
			else if(c == '}'){
				if(stk.top() == '{'){
					stk.pop();
				}
				else{
					check = true;
					break;
				}
			}
		}
		if(!stk.empty()){
			cout << "Illegal" << "\n";
		}
		else if(check){
			cout << "Illegal" << "\n";
		}
		else{
			cout << "Legal" << "\n";
		}
	}
	
	return 0;
}

이 문제는 다른 괄호 문제와 똑같은 문제인 듯 합니다.

getline(입력 스트림 오브젝트(ex: cin), string 배열 변수)를 사용해서 '공백'을 입력으로 포함시켜서 입력을 받도록 합니다.
또, '\n'으로 구분하기에 이번 문제에 사용하기 좋았습니다.

#을 입력받으면 종료이기에 break도 걸어주었습니다.

제대로된 것인지 아닌지를 확인하기 위해 check 변수를 만들었습니다.

입력받으면 여는 괄호가 나오면 스택에 넣어주고, 닫는 괄호가 나오면 스택 맨 위에 있는 괄호가 같은 종류의 괄호면 꺼냅니다.

닫는 괄호를 받았을 때, 스택 맨 위의 여는 괄호가 다르거나
모든 실행이 끝났을 때, 스택이 비어있지 않으면 Illegal인 것 입니다.

profile
반갑습니당~😄

0개의 댓글