LintCode "Delete Digits"

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 = ; int i = ;
while(i < n - )
{
if(A[i] > A[i + ])
{
A.erase(i, );
if(i > ) i--;
n --;
if(++cnt == k) break;
}
else
{
i ++;
}
}
if(cnt < k) // all ascending, remove last
{
n = A.size();
A = A.substr(, n - (k - cnt));
} // Remove leading 0s
i = , n = A.size();
while(i < n && A[i] == '') i ++;
A = A.substr(i);
if(A.empty()) A = ""; return A;
}
};
上一篇:数据库SQL优化大总结之 百万级数据库优化方案(转)


下一篇:数据库SQL优化大总结之 百万级数据库优化方案2