[2023년 11월 22일]큰 수 만들기(11분)

myeongrangcoding·2023년 11월 22일

프로그래머스

목록 보기
44/65

https://school.programmers.co.kr/learn/courses/30/lessons/42883

구현 아이디어 2분 구현 9분

풀이

뒤에 있는 큰 수 찾기와 같이 앞에 있는 큰 수를 유지하는 방법을 이용해 풀었다.

#include <string>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

string solution(string number, int k) {
    string answer = "";
    
    stack<int> result;
    for(int i = 0; i < number.size(); ++i)
    {
        int num = number[i] - '0';
        while(!result.empty() && k != 0)
        {
            if(num > result.top())
            {
                result.pop();
                --k;
            }
            else break;
        }
        result.push(num);
    }
    
    stack<int> tmp;
    while(!result.empty())
    {
        if(k != 0)
        {
            result.pop();
            --k;
            continue;
        }
        else tmp.push(result.top());
        result.pop();
    }
    
    while(!tmp.empty())
    {
        answer += tmp.top() + '0';
        tmp.pop();
    }
    
    return answer;
}
profile
명랑코딩!

0개의 댓글