402. 移掉K位数字

 1 class Solution 
 2 {
 3 public:
 4     string removeKdigits(string num, int k) 
 5     {
 6         if(num.size() == k) return "0";
 7         stack<char> stk;//单调栈
 8         string res;
 9 
10         for(int i = 0;i < num.size();++ i)//单调栈经典操作
11         {
12             while(!stk.empty() && stk.top() > num[i] && k > 0)
13             {
14                 stk.pop();
15                 -- k;
16             }
17             stk.push(num[i]);
18         }
19         //未删完
20         while(k --) stk.pop();
21 
22         //栈合成字符串
23         while(!stk.empty())
24         {
25             res = stk.top() + res;
26             stk.pop();
27         }
28 
29         //删除前缀"0"
30         while(!res.empty() && res.front() == '0') res.erase(res.begin());
31 
32         if(res.empty()) res = "0";
33         return res;
34     }
35 };

 

posted @ 2020-04-18 21:31  Jinxiaobo0509  阅读(103)  评论(0)    收藏  举报