402. Remove K Digits

http://www.cnblogs.com/grandyang/p/5883736.html
https://leetcode.com/problems/remove-k-digits/discuss/88660

Solution:

思路:

Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

public class Solution {
    public String removeKdigits(String num, int k) {
        int digits = num.length() - k;
        char[] stk = new char[num.length()];
        int top = 0;
        // k keeps track of how many characters we can remove
        // if the previous character in stk is larger than the current one
        // then removing it will get a smaller number
        // but we can only do so when k is larger than 0
        for (int i = 0; i < num.length(); ++i) {
            char c = num.charAt(i);
            while (top > 0 && stk[top-1] > c && k > 0) {
                top -= 1;
                k -= 1;
            }
            stk[top++] = c;
        }
        // find the index of first non-zero digit
        int idx = 0;
        while (idx < digits && stk[idx] == '0') idx++;
        return idx == digits? "0": new String(stk, idx, digits - idx);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,775评论 0 33
  • 我要路过一座坟我要垂下头一言不发给谁跪下,将傲骨摔碎我将面对高楼和荒野也许明天一场地震种种幻觉都将崩塌 重...
    子健阅读 618评论 4 4
  • 文/新浪微博@汪霁月 竹外桃花,纷纷飘落。卿舞霓裳,君弹曲。高山流水,绕指尖幽幽荡漾。执一叶扁舟,在岁月的河流上,...
    汪霁月阅读 273评论 0 1
  • 小妖是个摄影迷,非常喜欢拍照。但是却是个摄影白痴,角度掌握不好,不会P图,还不太会后期处理。然而小妖最大的优点...
    莫小妖阅读 595评论 0 1
  • 第一步,安装node,安装成功后打开命令行输入node -v检测安装版本 第二步,安装淘宝镜像 npm insta...
    唯有她美阅读 130评论 0 1