码迷,mamicode.com
首页 > 其他好文 > 详细

Remove K Digits

时间:2017-08-24 10:43:09      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:nbsp   pre   with   str   input   app   ringbuf   repr   bre   

题目:

  

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

标签:nbsp   pre   with   str   input   app   ringbuf   repr   bre   

原文地址:http://www.cnblogs.com/liulikecp3/p/7421302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!