Skip to main content

Command Palette

Search for a command to run...

removeKdigits

Published
1 min readView as Markdown
import java.util.Stack;

class Solution {
    public String removeKdigits(String n, int k) {
        Stack<Character> st = new Stack<>();

        for (int i = 0; i < n.length(); i++) {
            char c = n.charAt(i);
            while (k > 0 && !st.isEmpty() && st.peek() > c) {
                st.pop();
                k--;
            }
            st.push(c);
        }

        while (k > 0 && !st.isEmpty()) {
            st.pop();
            k--;
        }

        String res = "";
        for (char c : st) res += c;

        int idx = 0;
        while (idx < res.length() && res.charAt(idx) == '0') idx++;

        res = idx == res.length() ? "0" : res.substring(idx);
        return res;
    }
}

More from this blog

Amit singh's blog

235 posts