C++ Greedy


  • 0
    G
    class Solution {
    public:
        string removeKdigits(string num, int k) {
            int len=num.size();
            string res;
            if(len <= k) {
                return "0";
            }
            
            res=num;
            while(k--) {
                deleteChar(res);
            }
            
            trimStr(res);
            return res;
        }
        
        void trimStr(string & res) {
            int len = res.length();
    
            while(true) {
                int len=res.length();
                if(len < 2) {
                    break;
                }
                if(res[0] == '0') {
                    res.erase(res.begin());
                }
                else {
                    break;
                }
            }
        }
        
        void deleteChar(string & res) {
            int pos=getDeletePos(res);
            res.erase(res.begin() + pos);
        }
        
        int getDeletePos(string & num){
            int len=num.length();
            int i=0;
            for(i=0; i < len-1; i++) {
                if(num[i] > num[i+1]) {
                    break;
                }
            }
            return i;
        }
    };
    

Log in to reply
 

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