Greedy: remove earliest down-edge: like "54", "97".
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) { size_t n = A.size(); int cnt = 0; int i = 0; while(i < n - 1) { if(A[i] > A[i + 1]) { A.erase(i, 1); if(i > 0) i--; n --; if(++cnt == k) break; } else { i ++; } } if(cnt < k) // all ascending, remove last { n = A.size(); A = A.substr(0, n - (k - cnt)); } // Remove leading 0s i = 0, n = A.size(); while(i < n && A[i] == ‘0‘) i ++; A = A.substr(i); if(A.empty()) A = "0"; return A; } };
时间: 2024-10-23 09:47:58