[LeetCode] 402. Remove K Digits

来源:互联网 发布:文虎考堂 数据库 编辑:程序博客网 时间:2024/06/06 10:06

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:

Input: num = "1432219", k = 3Output: "1219"Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1Output: "200"Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2Output: "0"Explanation: Remove all the digits from the number and it is left with nothing which is 0.
class Solution {public:    string removeKdigits(string num, int k) {        int i = 0;        while (k > 0) {            for (; i + 1 < num.length() && num[i] <= num[i + 1]; i++)                ;            num.erase(i, 1);            k--;            i--;        }        while (num.length() > 1 && num[0] == '0')            num.erase(0, 1);        return num.length() == 0 ? "0" : num;    }};

这里写图片描述这里写图片描述

// 9msclass Solution {public:    string removeKdigits(string num, int k) {        if (num.length() == k) return string("0");        stack<char> stk;        for (auto letter : num) {            while (k > 0 && !stk.empty() && stk.top() > letter) {                stk.pop();                k--;            }            if (stk.empty() && letter == '0')                continue;            stk.push(letter);        }        while (k > 0) {            stk.pop();            k--;        }        string res;        while (!stk.empty()) {            res.insert(res.begin(), stk.top());            stk.pop();        }        return res.length() == 0 ? "0" : res;    }};
原创粉丝点击