풀이 보관함

[C++] 백준 5076번: Web Pages 본문

problem solving/백준

[C++] 백준 5076번: Web Pages

viin 2022. 7. 13. 19:34

문제

https://www.acmicpc.net/problem/5076

 

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

 

풀이

파싱하는게 제일 어려운 문제로 괄호 문제랑 비슷하게 풀었다. 

 

<tag> text </tag> 를 예시로 들겠다.

  • <tag>는 스택에 넣어준다. 
  • </tag>는 스택의 top과 비교한다. 
    •  top과 같다면 짝이 맞게 들어간 태그고 다르다면 짝지 맞지 않다.
  • <br />과 <a href=> </a>은 따로 처리 해주었다. (소스 참고)

 

+

 

한 줄 전체를 받기 위해서 std::cin이 아닌 std::getline(std::cin, v)를 사용해주었다.

소스

#include <iostream>
#include <string>
#include <stack>
int main()
{
    
    std::string text;
    while(1)
    {
        bool isLegal = true;
        std::stack<std::string> tags;
        std::getline(std::cin, text);
        if(text == "#"break;
        
        for(int i = 0; i<text.length(); ++i)
        {
            auto c = text[i];
            
            if(c == '<')
            {
                std::string tagname;
                for(int j = i+1; j<text.length(); ++j)
                {
                    if(text[j]=='>')
                    {
                        //</tag>
                        if((text.length() > i + 1&& text[i+1]=='/')
                        {
                            tagname = std::string(text.begin() + i+2, text.begin() + j);
                            
                            if((tags.empty() == false&& (tagname == tags.top()))
                                tags.pop();
                            else
                                isLegal = false;
                        }
                        else
                        {
                            
                            // not <br />
                            if(text[j-1!= '/')
                            {
                                //<a locat = ">
                                if((text.length() > i + 2 )&& text[i+2== ' ')
                                    tagname = std::string(text.begin() + i+1, text.begin() + 2);
                                else
                                    tagname = std::string(text.begin() + i+1, text.begin() + j);
                                
                                tags.push(tagname);
                            }
                            
                        }
                        break;
                    }
                }
                
                if(isLegal == false)
                    break;
                
            }
            
        }
        // 스택에 tag가 남아있다면 짝이 맞지 않은 것이다.
        if(isLegal || tags.empty())
            std::cout << "legal\n";
        else
            std::cout <<"illegal\n";
        
    }//while
    return 0;
}
 
cs