首页 > 其他 > 详细

LeetCode 402: Remove K Digits

时间:2017-10-08 16:47:17      阅读:245      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/shuashuashua/p/7637726.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!