码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 402: Remove K Digits

时间:2017-10-08 16:50:40      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:sub   empty   str   uil   asi   int   insert   length   tco   

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

标签:sub   empty   str   uil   asi   int   insert   length   tco   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!