算法设计与分析-Week19

Remove K Digits

题目描述

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:

Input: num = “1432219”, k = 3
Output: “1219”
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = “10200”, k = 1
Output: “200”
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = “10”, k = 2
Output: “0”
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

解题思路

本题要求在给定的数字字符串中,删除k个数字,得到的数最小。
可以用一个字符串模拟栈操作,遍历给定的字符串,对于每一个数字字符,将其与栈中的字符作比较,若比栈顶字符小,就弹出栈顶字符并继续比较,弹出的操作即为删除字符的操作,因此必须限定最多弹出k个字符。

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string removeKdigits(string num, int k) {
string ans = "";
for(char c: num) {
while(ans.length() && ans.back() > c && k) {
ans.pop_back();
k--;
}
if(ans.length() || c != '0') ans.push_back(c);
}
while(ans.length() && k--) ans.pop_back();
return ans.empty() ? "0" : ans;
}
};
0%