본문 바로가기

알고리즘/BOJ

[C++] 백준 3986번 - 좋은 단어


0. 문제

 

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

1. 아이디어

 

1) 입력값을 스택의 TOP()과 비교해서 같다면 POP 한다.

 

2) 만약, 중간에 거슬리는 값(선끼리 교차하게 하는 값)이 있다면, 그 값은 POP 되지 못하고 남아있는 값이다.

  

3) 최종적으로, 스택이 비어있다면 해당 단어는 교차하는 선이 없는 '좋은 단어' 이다!

 

2. 소스코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <stack>
int main()
{
    int N,result=0;
    std::cin >> N;
    for (int i = 0; i < N; i++)
    {
        std::stack<char> st;
        std::string str;
        std::cin >> str;
        for (int i = 0; i != str.length(); i++)
        {
            if (st.empty())
                st.push(str[i]);
            else
            {
                if (str[i] == st.top())
                    st.pop();
                else
                    st.push(str[i]);
            }
        }
        if (st.empty()) result++;
    }
    std::cout << result;
}
cs

 

3. 결과

 

4. 피드백

 

  • 문제를 의심하지 말고 일단 코딩부터 해보자