Share my C++ solution, easy to understand


  • 0
    V
    class Solution {
    public:
        string removeKdigits(string num, int k) {
            int len = num.length();
            int i = 0;
            
            if (k == len)
                return "0";
            
            while (k--)
            {
                i = 0;
                while (i + 1 < len && num[i] <= num[i + 1])
                    i++;
                
                num.erase(num.begin() + i);
            }
            
            i = 0;
            while (i < len && num[i] == '0')
                i++;
            if (i > 0)
                num.erase(num.begin(), num.begin() + i);
            if (num.length() == 0)
                return "0";
                
            return num;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.