remove-k-digits

https://leetcode.com/problems/remove-k-digits/

// 参考了这里的
// https://discuss.leetcode.com/topic/59327/o-n-solution/3

public class Solution {
    public String removeKdigits(String num, int k) {
        for (int i=0; i<num.length()-1 && k>0; i++) {
            // >=0 必须,因为会减2
            if (i>=0 && num.charAt(i) > num.charAt(i+1)) {
                num = num.substring(0, i) + num.substring(i+1);
                k--;
                i-=2;
            }
        }
        
        // 这一步必须
        while (!num.isEmpty() && num.charAt(0) == '0') {
            num = num.substring(1);
        }
        
        return num.length() - k >= 1 ? num.substring(0, num.length()-k) : "0";
    }
}

 

posted @ 2016-09-21 04:05  blcblc  阅读(234)  评论(0编辑  收藏  举报