Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"

Approach

Java

public class RemoveKDigits {
    public static void main(String[] args) {
        String num = "1432219";
        int k = 3;
        System.out.println(removeKdigits(num, k));
    }

    static String res;

    static void remove(String numint k) {
        // base case
        if (k == 0) {
            res = res + "" + num;
            return;
        }
        int n = num.length();

        // if k is greater than n then
        // return
        if (n <= k)
            return;
        int minIndex = 0;
        for (int i = 1; i <= k; i++) {
            if (num.charAt(i) < num.charAt(minIndex)) {
                minIndex = i;
            }
        }
        res = res + "" + num.charAt(minIndex);
        String new_string = num.substring(minIndex + 1,
                 minIndex + n - minIndex);
        remove(new_string, k - minIndex);

    }

//function to remove k digits from the number
    static String removeKdigits(String numint k) {
        res = "";
        String ans = "";
        remove(num, k);
        if (res.length() == 0)
            ans += "0";
        int i = 0;
        while (i < res.length() && res.charAt(i) == '0')
            i++;
        for (int j = i; j < res.length(); j++)
            ans += res.charAt(j);
        if (ans.length() == 0)
            ans += "0";
        return ans;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

void remove(string num,int k,string &res)
{
    //base case
     if(k==0)
        {
             res.append(num);
             return;
     }
    int n=num.size();

    //if k is greater than n then
    //return 
    if(n<=k)
        return;
    int minIndex=0;
    for(int i=1;i<=k;i++)
       {
         if(num[i]<num[minIndex])
          {
                minIndex=i;
          }
       }
     res.push_back(num[minIndex]);
     string  new_string=num.substr(minIndex+1,n-minIndex);
    remove(new_string,k-minIndex,res);
       
}

//function to remove k digits from the number
string removeKdigits(string numint k
{
        string res="",ans="";
        remove(num,k,res);
        if(res.size()==0)
              ans+="0";
        int i=0;
        while(res[i]=='0')
               i++;
        for(int j=i;j<res.size();j++)
                ans+=res[j];
        if(ans.size()==0)
              ans+="0";
        return ans;
}
int main()
{
   string num = "1432219";
   int k = 3;
   cout<<removeKdigits(num,k);
   return 0;
}



No comments:

Post a Comment