思路:
单调栈。
实现:
1 class Solution 2 { 3 public: 4 string removeKdigits(string num, int k) 5 { 6 stack<char> s; 7 int n = num.size(), r = k; 8 for (int i = 0; i < n; i++) 9 { 10 char x = num[i]; 11 while (r and !s.empty() and x < s.top()) 12 { 13 r--; s.pop(); 14 } 15 s.push(x); 16 } 17 string res = ""; 18 while (!s.empty()) 19 { 20 res += s.top(); s.pop(); 21 } 22 reverse(res.begin(), res.end()); 23 res = res.substr(0, n - k); 24 int p = 0, l = res.length(); 25 while (p < l and res[p] == '0') p++; 26 return p == l ? "0": res.substr(p, l - p); 27 } 28 };