Clear Java Solution Using Deque


  • 1
    H

    public class Solution {

     // the goal is to create an ascending sequence
    public String removeKdigits(String num, int k) {
        if (num == null || num.length() == 0) return "0";
        Deque<Character> nums = new LinkedList<>();
        char[] digits = num.toCharArray();
        for (int i = 0; i < digits.length; i++) {
            while (!nums.isEmpty() && k > 0 && digits[i] < nums.peekLast()) {
                nums.pollLast();
                k--;
            }
            nums.offer(digits[i]);
        }
        
        while (k > 0) {
            nums.pollLast();
            k--;
        }
        
        while (!nums.isEmpty() && nums.peek() == '0') {
            nums.poll();
        }
        
        StringBuilder sb = new StringBuilder();
        while (!nums.isEmpty()) {
            sb.append(nums.poll());
        }
        
        return sb.length() == 0 ? "0" : sb.toString();
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.