Level
LeetCode Medium
Recruitment
// 테케 27 실패

var removeKdigits = function (num, k) {
  const minSlice = (num, c) => {
    if (num.length === 2) {
      return Math.min(...num) + "";
    }

    const sliced = [num[0]];
    const numSize = num.length; // 4
    let coin = num.length - c;
    coin--;

    let i = 1;
    while (i < num.length && coin > 0) {
      let n = num[i];
      let remain = numSize - i;
      i++;

      if (remain > coin) {
        // 3 > 1
        let last = sliced.pop();

        if (last === n) {
          sliced.push(last);
          sliced.push(n);
          coin--;
          continue;
        }
        if (Math.min(last, n) == n) {
          sliced.push(n);
          continue;
        }
        if (Math.min(last, n) == last) {
          sliced.push(last);
          continue;
        }
      }

      sliced.push(n);
      coin--;
    }
    return sliced.join("");
  };

  const filtZero = (num) => {
    let i = 0;
    for (const c of num) {
      if (c === "0") {
        i++;
      } else {
        break;
      }
    }
    const sliced = num.slice(i);
    return sliced || "0";
  };

  let coin = k;
  let ans = num;

  while (coin > 0) {
    const zero = ans.indexOf("0");

    if (zero === -1) {
      return ans.length <= coin ? "0" : minSlice(ans, coin);
    }

    const before = ans.slice(0, zero);
    const after = ans.slice(zero);

    if (before.length === coin) {
      return filtZero(after);
    }

    if (before.length > coin) {
      return minSlice(before, coin) + after;
    }

    if (before.length < coin) {
      if (after == 0 || after === "") {
        return "0";
      }
      ans = filtZero(after);
      coin = coin - before.length;
    }
  }

  return ans;
};