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,

xample

Given an integer A = "178542", k = 4

return a string "12"

首先要理解題目的意思,題目是說在原整數的順序基礎上刪除,刪除之後要保留之前的順序。那如何才能確定某個數該刪除,假如有個整數453,現在要刪除一個元素,如何選擇刪除一個元素使得數最小,我們人工會選擇刪除5,得到43;那爲什麼這樣刪除可以保證得到滿足題意的結果,假如現在在位置4處,如果刪除4會使得到53,如果不刪除4,刪除5,會得到43,也就是說對於i位置的數a[i] <= a[i + 1], 那麼不應該刪除i處的數,因爲刪除i處的數比刪除i+1處的數更大,所以不能刪除第i處的數;反之則應該刪除;這樣就有了如何確定某個數是否應該刪除的數學依據。在實現的時候,很多細節需要考慮。

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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章