leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0402.cpp (823B)


      1 class Solution {
      2     class Solution {
      3       public:
      4         string removeKdigits(string num, int k) {
      5             if (num.length() <= k) return "0";
      6             if (k == 0) return num;
      7 
      8             string res = "";
      9             stack<char> s;
     10 
     11             s.push(num[0]);
     12             for (int i = 1; i < num.length(); ++i) {
     13                 while (k > 0 && !s.empty() && num[i] < s.top()) {
     14                     --k;
     15                     s.pop();
     16                 }
     17                 s.push(num[i]);
     18                 if (s.size() == 1 && num[i] == '0') s.pop();
     19             }
     20 
     21             while (k && !s.empty())
     22                 --k, s.pop();
     23 
     24             while (!s.empty())
     25                 res.push_back(s.top()), s.pop();
     26 
     27             reverse(res.begin(), res.end());
     28             return res.size() ? res : "0";
     29         }
     30     };