Remove K Digits

Remove K Digits

Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.

LeetCode Problem - 402

import java.util.*;

class Solution {
    public String removeKdigits(String num, int k) {
        // Create a stack to store digits
        Stack<Character> stack = new Stack<>();

        // Iterate through each digit in the number
        for (char digit : num.toCharArray()) {
            // Remove digits from the stack if they are greater than the current digit and k > 0
            while (k > 0 && !stack.isEmpty() && stack.peek() > digit) {
                stack.pop();
                k--;
            }

            // Push the current digit onto the stack
            stack.push(digit);
        }

        // Remove remaining digits from the stack if k is still greater than 0
        while (k > 0) {
            stack.pop();
            k--;
        }

        // Build the result string using StringBuilder
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.insert(0, stack.pop());
        }

        // Remove leading zeros from the result
        while (result.length() > 0 && result.charAt(0) == '0') {
            result.deleteCharAt(0);
        }

        // If result is empty, return "0", otherwise return the result
        return result.length() == 0 ? "0" : result.toString();
    }
}