首页 > 其他 > 详细

leetcode402 移掉k位数字

时间:2021-04-26 15:53:34      阅读:24      评论:0      收藏:0      [点我收藏+]

思路:

单调栈。

实现:

 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 };

leetcode402 移掉k位数字

原文:https://www.cnblogs.com/wangyiming/p/14703876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!