작심 24/7

[백준] 5076번 Web Pages 본문

백준

[백준] 5076번 Web Pages

모닝수박 2020. 6. 5. 23:08
 

5076번: Web Pages

Input will consist of a number of lines of HTML code, each line containing from 0 to 255 characters. The last line will contain a single # character – do not process this line. Within the text of each line will be zero or more tags. No angle bracket will

www.acmicpc.net

문제의 조건들을 나열해보면

 

1. 열린 태그와 닫힌 태그의 쌍이 맞아야 한다.

<body> <strong> </body> </strong> (X)

<body> <strong> </strong> </body> (O)

 

2. 한 태그 안에서 열고 닫을 수 있다.

<br />

 

3. 열린 태그 안에 문법이 들어갈 수 있다.

<a href="abcd">

 

4. 올바르지 못한 형태의 태그는 나오지 않는다.

 

5. 태그가 나오지 않을 수도 있다.

 

6. 0자~255자의 글자가 입력된다.

=> null값이 입력될 경우도 생각해줘야 한다.

 

 

6번의 null값이 나오는 경우를 위해 공백, 개행 포함 입력되는

cin.getline 함수를 사용해준다.

 

열린 태그가 시작될 때 조건에 맞게 필터링 해준 다음

태그 안의 키워드만 stack에 push해준다.

 

닫힌 태그가 시작될 때도 조건에 맞게 필터링 해준 뒤

태그 안의 키워드만 가져와 stack값과 비교한다.

 

stack의 top과 닫힌 태그의 키워드가 같지 않다면

1번 조건에 맞지 않으므로 illegal이고 같으면 다음으로 넘어간다.

 

문자열의 끝까지 비교했는데 stack이 empty인 상태면

legal, 아니면 illegal.

 

조건을 꼼꼼히 파악하는 게 중요하다.

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
	while (1) {
		char input[256];
		cin.getline(input, 256);

		if (input[0] == '#') break;

		stack <string> html;
		for (int i = 0; i < 256; i++) {
			string temp;
			if (input[i] == '<') {
				if (input[i + 1] == '/') { //닫히는 구문
					i++;
					while (1) {
						i++;
						if (input[i] == '>') break;
						temp += input[i];
					}
					if (!html.empty() && html.top() == temp) html.pop();
					else {
						cout << "illegal\n";
						break;
					}
				}
				else { //시작하는 구문
					int no = 0, blank = 0;
					while (1) {
						i++;
						if (input[i] == '/' && input[i + 1] == '>') no++;
						if (input[i] == ' ') blank++;
						if (input[i] == '>') break;
						if (blank == 0) temp += input[i];
					}
					if (no == 0) html.push(temp);
				}
			}
			if (html.empty() && input[i] == NULL) {
				cout << "legal\n";
				break;
			}
			else if (!html.empty() && input[i] == NULL) {
				cout << "illegal\n";
				break;
			}
		}
	}
	return 0;
}

'백준' 카테고리의 다른 글

[백준] 1912번 연속합  (0) 2020.06.07
[백준] 1406번 에디터  (0) 2020.06.06
[백준] 2841번 외계인의 기타 연주  (0) 2020.06.05
[백준] 2304번 창고 다각형  (4) 2020.06.05
[백준] 1725번 히스토그램  (0) 2020.06.05
Comments