402. Remove K Digits

Description

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Note:

  • The length of num is less than 10002 and will be ≥ k.
  • The given num does not contain any leading zero.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

Solution

Greedy & Stack, time O(n), space O(n)

假设num的组成是"abc.....",如果删掉'a',那么剩下的是"bc....",一定是由b打头;如果删掉任何a之后的字符,剩下的string必定由a打头。于是比较a和b的大小即可,用Greedy的思路选择最优解即可。

注意需要考虑a = b的情况,在这种情况下需要先遍历到后面的元素才知道怎么处理a和b(考虑"223"和"221"),所以用Stack来实现就显得很合理了。

class Solution {
    public String removeKdigits(String num, int k) {
        if ("0".equals(num) || k < 1) {
            return num;
        }
        
        Stack<Character> stack = new Stack<>();
        for (char c : num.toCharArray()) {
            // whenever meet a digit which is less than the previous digit, 
            // discard the previous one to keep chars in stack are in asc order
            while (k > 0 && !stack.empty() && stack.peek() > c) {
                stack.pop();
                --k;
            }
            
            if (stack.empty() && c == '0') {    // discard '0' at the head
                continue;
            }
            
            stack.push(c);
        }
        
        while (!stack.empty() && k-- > 0) {     // corner case "1234", 2
            stack.pop();
        }
        
        StringBuilder sb = new StringBuilder();
        while (!stack.empty()) {
            sb.insert(0, stack.pop());  // construct number
        }
        
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 402. Remove K Digits Given a non-negative integer num rep...
    Jonddy阅读 630评论 0 0
  • 小时候 幸福就是一块糖果 也是隔壁小朋友手里的玩具 上学后 幸福就是作业本上红色的勾 也是隔壁班姑娘害羞的一个微笑...
    刘里墨阅读 377评论 5 3
  • 村头古树下青草叶上 露水未凝干,晨雾里渡船唱着歌谣 撑过小河湾,我枕着手臂躺在屋顶 想了一整晚,瓦下厅堂中谁又说起...
    稻场旧事阅读 915评论 9 10
  • 在开发中,我们iOS在定义属性的时候,需要在括号property()内说明该属性的特性,因为属性的特性决定了属性在...
    杰森_Jason阅读 1,083评论 0 3
  • 爷爷今年89岁了,一生养育了四个子女,父亲是爷爷唯一的儿子,也是最小的孩子,而且是在奶奶四十三岁高龄生育的,父亲与...
    wakinggirl阅读 669评论 0 5