Saturday, May 30, 2015

[LintCode] Delete Digits

Given string A representative a positive integer which has Ndigits, 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,

Example


Given an integer A = "178542", k = 4
return a string "12"
class Solution {
public:
    string DeleteDigits(string A, int k) {
        if(A.length() < k) return A;

        int j = 0;
        while(j < A.length()-1 && k > 0)
        {
            if(A[j]>A[j+1]){
                A.erase(j,1);
                k--;     
                if(j>0)j--;
            }
            else j++;
        }
        A = A.substr(0, A.length()-k);
        int index = A.find_first_not_of("0");
        return A.substr(index);
    }
};