LeetCode 402: Remove K Digits

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 402: Remove K Digits相关的知识,希望对你有一定的参考价值。

Note:

1. Find a increasing digits number. It‘s kind of longest increasing subsequence but with fixed size.

2. Remember to remove the zeros from beginning.

class Solution {
    public String removeKdigits(String num, int k) {
        if (num.length() == 0) return "0";
        int i = 1;
        Stack<Character> stack = new Stack<>();
        stack.push(num.charAt(0));
        while (i < num.length()) {
            while (k > 0 && !stack.isEmpty() && num.charAt(i) < stack.peek()) {
                k--;
                stack.pop();
            }
            stack.push(num.charAt(i++));
        }
        
        while (k > 0 && !stack.isEmpty()) {
            stack.pop();
            k--;
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            result.insert(0, stack.pop());
        }
        while (result.length() > 1 && result.charAt(0) == ‘0‘) result.deleteCharAt(0);
        return result.length() == 0 ? "0" : result.toString();
    }
}

 

以上是关于LeetCode 402: Remove K Digits的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 402: Remove K Digits

[栈] leetcode 402 Remove K Digits

每日一题- Leetcode 402. Remove K Digits

每日一题- Leetcode 402. Remove K Digits

402. Remove K Digits

402. Remove K Digits