原题链接:https://leetcode.com/problems/remove-k-digits/description/
题目描述:
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 thedigits from the number and it is left with nothing which is 0.
Solution: 我们可以采用贪心法的思路。举个例子,在第一个样例中,num = “1432219”, k = 3, 那么产生的结果应该是一个四位数。对于这个四位数的每一位,都有一个有限的选择范围,比如说,在此例子中,四位数的千位的范围只能是num[0~3],而百位只能从千位选择的数的下一位开始选,一直到num[4],当千位选择num[0]中的1时,那么百位的选择范围就是num[1~4]。依次类推,结果的每一个数位都有一个选择范围,我们只需要对每一个数位,都尽可能地在期选择范围内选择最小的数即可。
class Solution {
public:
string trim(string num) {
string result;
bool flag = true;
for (int i = 0; i < num.size(); ++i)
if (num[i] == '0' && flag) ;
else {
flag = false;
result += num[i];
}
if (result.empty()) result = "0";
return result;
}
string removeKdigits(string num, int k) {
string result = "";
int size = num.size();
int start_index = 0;
int end_index;
for (int i = 0; i < size - k; i++) {
end_index = k + i;
int j = start_index;
int min_index = -1;
char min_element = '9' + 1;
while (j <= end_index) {
if (num.at(j) < min_element) {
min_element = num.at(j);
min_index = j;
}
j++;
}
result += num[min_index];
start_index = min_index + 1;
}
return trim(result);
}
};
算法分析: 对一个n位数,产生的结果有n-k位,每一个数位的选择范围最大是k,所以复杂度大约有O(k*n)。
改进: Well, one can simply scan from left to right, and remove the first “peak” digit; the peak digit is larger than its right neighbor. One can repeat this procedure k times, and obtain the algorithm.
string removeKdigits(string num, int k) {
string res;
int keep = num.size() - k;
for (int i=0; i<num.size(); i++) {
while (res.size()>0 && res.back()>num[i] && k>0) {
res.pop_back();
k--;
}
res.push_back(num[i]);
}
res.erase(keep, string::npos);
// trim leading zeros
int s = 0;
while (s<(int)res.size()-1 && res[s]=='0') s++;
res.erase(0, s);
return res=="" ? "0" : res;
}