Wednesday, 5 October 2016

Remove K Digits (LeetCode)

Problem: Remove K Digits

class Solution {
public:
    string removeKdigits(string num, int k) {
        if(k==0) return num;
        if(num.length()==1) return "0";
        
        while(k--)
        {
            if(num.length()<=1)
            {
                num="0";
                continue;
            }
            
            bool removed = false;
            for(int i=0;i<num.length()-1;i++)
                if(num[i]>num[i+1])
                {
                    num.erase(i, 1);
                    removed = true;
                    break;
                }
            if(!removed) num.erase(num.size()-1, 1);
        }
        while(num[0]=='0' && num.size()>1) num.erase(0,1);
        return num;
    }
};

No comments:

Post a Comment