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,
xample
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
int lenA = A.size();
if(lenA < k || lenA == k)
return "";
if(k <= 0)
return A;
string ans = "";
int index = 0;
while(index < lenA){
if(index < (lenA - 1)){
if(A[index] <= A[index + 1])
{
if(ans.size() > 0 || A[index] != '0')
ans.push_back(A[index]);
}
else if(A[index] > A[index + 1] && k > 0){
--k;
<span style="white-space:pre"> </span> //對於之前沒有刪除的數,需要檢查是否也要刪除
while(ans.size() && k > 0 && ans[ans.size() - 1] > A[index + 1]){
--k;
ans.pop_back();
}
}
else
ans.push_back(A[index]);
}
else
ans.push_back(A[index]);
++index;
}
//如果出現了ans爲遞增序列,而且刪除數不夠,則直接從ans後面刪除較大的數
while(k > 0){
ans.pop_back();
--k;
}
return ans;
}
};