Advertisement
Marvin48

remove k digits 2

Dec 26th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. //https://leetcode.com/problems/remove-k-digits/description/
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. class Solution {
  8. private:
  9.     inline void AddDigit(string &ret, char c, bool &leadingZeroes) {
  10.         if (!leadingZeroes || c != '0') {
  11.             ret += c;
  12.             leadingZeroes = false;
  13.         }
  14.     }
  15.    
  16. public:
  17.     string removeKdigits(string nums, int k) {
  18.         if (nums.size() == k)
  19.             return "0";
  20.        
  21.         string ret = "";
  22.         char lastCh = '#';
  23.         bool leadingZeroes = true;
  24.        
  25.         //remove all digits greater then the following one while k > 0
  26.         for (char c : nums) {
  27.             if (lastCh == '#') {
  28.                 lastCh = c;
  29.                 continue;
  30.             }
  31.            
  32.             if (lastCh <= c) {
  33.                 AddDigit(ret, lastCh, leadingZeroes);
  34.                 lastCh = c;
  35.             }
  36.             else {
  37.                 if (k > 0)
  38.                     k--;
  39.                 else
  40.                     AddDigit(ret, lastCh, leadingZeroes);
  41.                 lastCh = c;
  42.             }
  43.         }
  44.         AddDigit(ret, lastCh, leadingZeroes);
  45.        
  46.         //trim digits from the end, skip zeroes
  47.         if (k > 0)
  48.             for (long i = ret.size() - 1; i >= 0; i--) {
  49.                 if (ret[i] != '0') {
  50.                     ret.erase(i, 1);
  51.                     k--;
  52.                 }
  53.                 if (k == 0)
  54.                     break;
  55.             }
  56.        
  57.         if (ret == "")
  58.             ret = "0";
  59.        
  60.         return ret;
  61.     }
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement