zoukankan      html  css  js  c++  java
  • 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 = 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;
        }
    };
  • 相关阅读:
    数组和函数
    循环练习题
    JavaScript 循环
    函数
    JavaScript简介2
    JS练习题1
    JavaScript简介
    css样式综合
    格式与布局
    列表和方块
  • 原文地址:https://www.cnblogs.com/tonix/p/4855257.html
Copyright © 2011-2022 走看看