Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
Example 1:
Example 2:
Example 3:
解法1: 贪心算法
这题用贪心的算法, 观察可以发现如果每次remove的时候满足if (num[i] > num[i + 1])
, 那么得到的数一定是最小的.
这里可以用一个string来存储当前扫描的结果,如果发现现在的字符比string的最后一个字符小,那么就把string的最后一个字符去掉. (目的是维护一个递增的数列)
最后呢,我们只需要去前num.size() - k
个数即可.要注意的是因为每次去除数字的时候k数会变,所以一开始需要用一个变量存储初值.
最后返回的时候要去掉leading zero.
C++
Java