Remove K Digits

Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.

Find the smallest integer after remove k digits.

N <= 240 and k <= N,

Example

Given an integer A = "178542", k = 4

return a string "12"

Analysis:

When take current number n from string A, we need to compare the last digit we have in the new string, if n is greater than the last number in the new string, we do nothing. However, if n is less than the last digit in the new string, should we replace it? we can if we have

newString.length() + A.length() - p > A.length() - k.

 1 class Solution {
 2     public String removeKdigits(String num, int k) {
 3         if (num == null || num.length() == 0 || k <= 0) return num;
 4         if (num.length() <= k) return "0";
 6         StringBuilder sb = new StringBuilder(); 8         
 9         for (int p = 1; p < num.length(); p++) {
10             //这题关键的部分是如果当前这个数比前一个数小,我们就一定要把当前这个数替换掉前一个数。因为这样我们得到的数就一定更小。
11             // 但是也不是可以无限替换,我们得保证num后面部分的substring长度+当前sb的长度 >= num.length() - k
12             while (sb.length() >= 1 && num.charAt(p) < sb.charAt(sb.length() - 1) && sb.length() > p - k) {
13                 sb.deleteCharAt(sb.length() - 1);
14             }
15             if (sb.length() < num.length() - k) {
16                 sb.append(num.charAt(p));
17             }
18         }
19         // remove the extra 0 at the beginning
20         while(sb.length() > 1 && sb.charAt(0) == '0') {
21             sb.deleteCharAt(0);
22         }
23         return sb.toString();
24     }
25 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5672239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值