LintCode Delete Digits
Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.
Find the smallest integer after remove k digits.
N <= 240 and k <= N,
Have you met this question in a real interview? Yes
Example
Given an integer A = "178542", k = 4
return a string "12"
class Solution {
public:
/**
*@param A: A positive integer which has N digits, A is a string.
*@param k: Remove k digits.
*@return: A string
*/
string DeleteDigits(string A, int k) {
// wirte your code here
string res;
int deleted = 0;
int len = A.size();
for (int i = 0; i < len; i++) {
while (!res.empty() && res.back() > A[i] && deleted < k) {
res.pop_back();
deleted++;
}
if (res.empty() && A[i] == '0') {
continue;
}
res.push_back(A[i]);
}
return res.substr(0, res.size() - (k - deleted));
}
};
前导零的删除不计入删除字符数