Remove K Digits

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

Note:

  • The length of num is less than 10002 and will be ≥ k.
  • The given num does not contain any leading zero.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

 

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

 

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.


public String removeKdigits(String num, int k) {
  /**
  *用StringBuffer当做栈
  *向栈中加入元素,如果新加入的元素小于栈顶元素弹出
  */
  StringBuffer result = new StringBuffer();
  int count = k, i;
  for (i = 0; i < num.length(); ++i) {
    while (result.length() > 0 && count > 0 && num.charAt(i) < result.charAt(result.length() - 1)) {
      result.deleteCharAt(result.length() - 1);
      count--;
    }
    result.append(num.charAt(i));
  }
  for (i=0;i<result.length();++i) { //删除结果中开始多余的0
    if (result.charAt(i) != ‘0‘) {
      break;
    }
  }
  //计算结果字符串 //如果结果中全是0,防止数组过界
  String re = result.substring(Math.min(i,result.length()-count), result.length() - count);
  return re.equalsIgnoreCase("") ? "0" : re; //处理结果为空的情况
}

以上是关于Remove K Digits的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode402. Remove K Digits

402. Remove K Digits

402. Remove K Digits

[栈] leetcode 402 Remove K Digits

402. Remove K Digits - Medium

[LeetCode] Remove K Digits 去掉K位数字