[프로그래머스]큰 수 만들기

allnight5·2023년 2월 28일
0

프로그래머스

목록 보기
39/73

링크

자바

import java.util.*;
class Solution {
    public String solution(String number, int k) {
        String answer = "";
        String answer2 = "";
        Stack<String> stack = new Stack<>();
        String[] numbers = number.split("");
        Stack<String> stack2 = new Stack<>();
        for(int i=numbers.length-1; i>=0;i--){
            stack2.push(numbers[i]);
        }   
        while(!stack2.isEmpty() && k>0){ 
            stack.push(stack2.pop()); 
            if(!stack2.isEmpty() && !stack2.isEmpty()){ 
                while( Integer.valueOf(stack.peek())< Integer.valueOf(stack2.peek())&&k>0){ 
                    stack.pop();
                    k -= 1; 
                    if (stack.isEmpty()) {
                        break;
                    }
                }
            } 
        }
        while(k>0){
            stack.pop();
            k -= 1;
        }
        while (stack.size() > 0) {
            answer = stack.pop() + answer;
        }
        while(stack2.size()>0){
            answer2 = answer2+ stack2.pop();
        } 
        return answer + answer2;
    }
} 

파이썬

from collections import deque
def solution(number, k):
    q = deque()
    stack = deque()
    
    for n in number :
        q.append(n)

    while q and k:
        while stack and stack[-1] < q[0]:
            stack.pop()
            k -= 1
            if not k:
                break
        stack.append(q.popleft())

    while k and stack:
        stack.pop()
        k -= 1

    return "".join(stack + q)
profile
공부기록하기

0개의 댓글