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

402. Remove K Digits

时间:2017-10-25 00:34:36      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:desc   ++   rem   har   pre   元素   class   ack   int   

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.

 题目含义:给定的整数中删除k位后尽可能得到最小值

 1     public String removeKdigits(String num, int k) {
 2         Stack<Character> digs = new Stack<>();
 3         int length = num.length();
 4         if (k == 0) return num;
 5         if (k == length) return "0";
 6         int i = 0;
 7         while (i < length) {
 8 
 9             while (k > 0 && !digs.isEmpty() && num.charAt(i) < digs.peek()) {
10                 //保证顶上的元素小于等于num.charAt(i)
11                 digs.pop();
12                 k--; //相当于删除一位较大的值
13             }
14             digs.push(num.charAt(i));//保证栈从顶到低的值是递减的
15             i++;
16         }
17         while (k > 0) { //k为数字还没有删除够,继续删除
18             digs.pop();
19             k--;
20         }
21         StringBuilder sb = new StringBuilder();
22         while (!digs.isEmpty()) {
23             sb.append(digs.pop()); //构成由高到底的字符串
24         }
25         sb.reverse();//翻转成由底到高的字符串,因为在push的时候是按照i顺序push的,所以反转后的字符串中每个字符的先后顺序和原来保持一致
26         while (sb.length() > 1 && sb.charAt(0) == ‘0‘) {
27             sb.deleteCharAt(0);
28         }
29         return sb.toString();        
30     }

 

 

 

 

402. Remove K Digits

标签:desc   ++   rem   har   pre   元素   class   ack   int   

原文地址:http://www.cnblogs.com/wzj4858/p/7726044.html

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