Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //https://leetcode.com/problems/remove-k-digits/description/
- #include <iostream>
- using namespace std;
- class Solution {
- private:
- inline void AddDigit(string &ret, char c, bool &leadingZeroes) {
- if (!leadingZeroes || c != '0') {
- ret += c;
- leadingZeroes = false;
- }
- }
- public:
- string removeKdigits(string nums, int k) {
- if (nums.size() == k)
- return "0";
- string ret = "";
- char lastCh = '#';
- bool leadingZeroes = true;
- //remove all digits greater then the following one while k > 0
- for (char c : nums) {
- if (lastCh == '#') {
- lastCh = c;
- continue;
- }
- if (lastCh <= c) {
- AddDigit(ret, lastCh, leadingZeroes);
- lastCh = c;
- }
- else {
- if (k > 0)
- k--;
- else
- AddDigit(ret, lastCh, leadingZeroes);
- lastCh = c;
- }
- }
- AddDigit(ret, lastCh, leadingZeroes);
- //trim digits from the end, skip zeroes
- if (k > 0)
- for (long i = ret.size() - 1; i >= 0; i--) {
- if (ret[i] != '0') {
- ret.erase(i, 1);
- k--;
- }
- if (k == 0)
- break;
- }
- if (ret == "")
- ret = "0";
- return ret;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement