How to get the least number after deleting k digits from the input number

前端 未结 11 1215
灰色年华
灰色年华 2020-12-11 05:34

For example, if the input number is 24635, the least number is 23 after deleting any 3 digits.

It\'s not the same as taking the two smalles

11条回答
  •  情话喂你
    2020-12-11 05:41

    To solve this, you can follow these steps −

    • Define a stack st, create an empty string ret

    • n := size of num

    • for i in range 0 to n – 1

    • while k is non zero and stack is not empty and top of stack > num[i]

    • delete from the stack and decrease k by 1

    • insert num[i] into st

    • while k is not 0, delete element from the stack

    • while the stack is not empty

    • ret := ret + top of stack, delete element from stack

    • now reverse the ret string

    • ans := an empty string, and i := 0

    • while i < size of ret and ret[i] is not ‘0’

    • increase i by 1

    • for i < size of ret

    • ans := ans + ret[i]

    • ret := ans

    • return “0” if size of ret is 0, otherwise, ret

    C++ solution:

    class Solution {
    public:
       string removeKdigits(string num, int k) {
          stack st;
          string ret = "";
          int n = num.size();
          for(int i = 0; i < n; i++){
             while(k && !st.empty() && st.top() > num[i]){
                st.pop();
                k--;
             }
             st.push(num[i]);
          }
          while(k--)st.pop();
          while(!st.empty()){
             ret += st.top();
             st.pop();
          }
          reverse(ret.begin(), ret.end());
          string ans = "";
          int i = 0;
          while(i 

提交回复
热议问题