前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 0402 - Remove K Digits

LeetCode 0402 - Remove K Digits

作者头像
Reck Zhang
发布2021-08-11 11:11:06
2230
发布2021-08-11 11:11:06
举报
文章被收录于专栏:Reck Zhang

Remove K Digits

Desicription

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

代码语言:javascript
复制
class Solution {
public:
    std::string removeKdigits(const std::string& num, int k) {
        std::stack<char> mono{};
        for(const auto& c : num) {
            while(!mono.empty() && mono.top() > c && k > 0) {
                mono.pop();
                k--;
            }
            mono.push(c);
        }
        while(!mono.empty() && k > 0) {
            mono.pop();
            k--;
        }

        std::string res = std::string(mono.size(), 'a');
        for(int i = mono.size() - 1; i >= 0; i--) {
            res[i] = mono.top();
            mono.pop();
        }
        int index = 0;
        for(; index < res.size(); index++) {
            if(res[index] != '0') {
                break;
            }
        }
        return res.empty() ? std::string{"0"} : res.substr(index).empty() ? std::string{"0"} : res.substr(index);
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Remove K Digits
    • Desicription
      • Solution
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档