Hamutaro
코테 좀 해라★彡/C++

짝지어 제거하기

요미 ★ 2024. 4. 2.

#include <iostream>
#include<string>
using namespace std;

int solution(string s)
{
    int answer = -1;
    
    if(s.size() <= 1) return 0;
    
    string checkS = "_";
    while(checkS!="")
    {
        checkS="";
        bool isTrue = false;
        int idx = -1;
        for(int i = 0 ; i<s.size()-1;i++)
        {
            if(s[i] == s[i+1] && !isTrue)
            {
                isTrue = true;
                checkS += s.substr(i+2,s.size());
                break;
            }
            else
            {
                checkS += s[i];  
            }
        }

        if(!isTrue) return 0;
        s=checkS;
    }

    return 1;
}

 

.. 힝 ㅜ

ㅜ 보니까 효율성때문에 stack으로 풀어줘야한다 

#include <stack>
#include <string>
using namespace std;

int solution(string s)
{
	stack<char> st;

	for (int i = 0; i < s.size(); ++i)
	{
		if (st.empty())
			st.push(s[i]);

		else if (st.top() == s[i])
			st.pop();

		else
			st.push(s[i]);
	}

    return st.empty();
}

 

짝짓는 문제는 stack을 사용하면 효율적일 것 같다.

'코테 좀 해라★彡 > C++' 카테고리의 다른 글

피보나치 수  (0) 2024.04.02
다음 큰 숫자  (1) 2024.04.01
숫자의 표현  (0) 2024.04.01
이진 변환 반복하기  (1) 2024.03.28
올바른 괄호  (1) 2024.03.28

댓글