[LeetCode]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,


Example
Given an integer A = “178542”, k = 4
return a string “12”


解題思路

貪心的思想,從左到右掃描字符串,如果A[i] > A[i+1]則刪除A[i],直至刪除了k個數字爲止。這樣就能使得越小的數字排在最左邊,從而使得刪除了k個數字後的數最小。

⚠注意兩個特殊情況:

  1. 如果掃描了一遍以後,已經刪除了的數字(deleted_num)小於k個,甚至是A中所有數字升序排列,沒有A[i] > A[i+1]的情況(此時deleted_num = 0),則要刪除末尾的(k - deleted_num)個字符。
    eg. 測試樣例: A = “12345”, k = 2
  2. 執行了上述算法後,還需進行後處理,刪除首位的零。
    eg. 測試樣例: A = “90249”, k = 2
    輸出應該是“24”,而不是“024”

代碼如下:

#include <string>
#include <iostream>

using namespace std;

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 deleted_num = 0;
        int n = A.size();
        if(!A.empty() && n <= 240 && k < n){
            for(auto i = A.begin(); i != A.end() - 1;){
                if(*i > *(i + 1)){
                    A.erase(i);
                    deleted_num++;
                    if(i != A.begin())
                        i--;
                    if(deleted_num == k)
                        break;
                }
                else
                    i++;
            }
            //⚠1
            if(deleted_num < k){
                A.erase(A.end() - (k - deleted_num), A.end());
            }
            //⚠2
            auto i = A.begin();
            while(*i == '0')
                A.erase(i);
        }

        return A;

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