题目:
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.
思路:
贪心算法:扫描一遍字符串,如果当前字符比结果字符串的最后一个字符要小,并且还可以再删除,那么就删除结果字符串的最后一个字符,直到没有可以删除的字符,就将当前字符加入结果字符串中。怎么分析时间复杂度呢?由于每个字符最多在while循环中被弹出一次,所以for循环中的while循环最多也就执行O(n)次,因此总的时间复杂度仍然是O(n)。空间复杂度也是O(n)(因为临时结果集中有可能需要存贮额外的字符)。
这道题目理论上是用stack来解答的,虽然我下面的代码没有采用stack,但是实际上是用vector来模拟stack了^_^(STL中的string是用vector来做底层表示的)。
代码:
class Solution {
public:
string removeKdigits(string num, int k) {
string ans;
int n = k, len = num.size(), cnt = 0;
for(auto val : num) {
while(!ans.empty() && n > 0 && val < ans.back()) {
--n;
ans.pop_back();
}
ans.push_back(val);
}
while(ans[cnt] == '0') {
cnt++;
}
ans = ans.substr(cnt, len - k - cnt);
return ans.size() > 0 ? ans : "0";
}
};