[LeetCode]402. Remove K Digits

来源:互联网 发布:php 微信开发 编辑:程序博客网 时间:2024/06/05 16:45

问题链接

问题描述

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 个数字使得剩余数字组成的整数尽可能的小。
注意:

  • 给定的整数长度 length 满足 10002 > length >= k
  • 给定的整数字符串头部不包含 0,返回的结果也需要满足头部不包含 0 的条件

例如:
输入: num = “1432219”, k = 3
输出:”1219”
解答:移除 3 个数字 4, 3, 和 2, 形成最小的新整数 1219


思路
怎么样才能得出最小的整数呢?比如说 “1432219”,首先考虑移除大数,比如这里最大的是 9,再考虑移除高位,结合起来就是移除高位大数。所以我们从高位开始,如果高位的数大于低位的数,就移除,因为移除高位,低位就自然而然占据了高位的位置,且数值更小。到这里就已经可以看出有贪心算法的性质了。用例子来解释就是:

  • 1432219 从最高位开始,1 < 4,不处理,接着遍历
  • 4 > 3,移除 4,得到 132219
  • 3 > 2,移除 3,得到 12219
  • 2 = 2,跳过,2 > 1,移除 2,得到 1219

最后还要注意清除头部的 0


代码实现

public class Solution {    public String removeKdigits(String num, int k) {        if (num.length() == k) return "0";        StringBuilder sb = new StringBuilder(num);        int i = 0;        while (k > 0) {            if (i == sb.length() - 1) {                //如果指针已经到达字符串末尾,且末尾数字为 0,则直接返回 "0"                //因为 0 是最小的,如果指针已经到达尾部,且末尾数字为0,说明前面的数字都等于0,或者是字符串只剩一个0                if (sb.charAt(i) == '0') {                    return "0";                } else {                    sb.deleteCharAt(i);                    i--;                    k--;                    continue;                }            }            if (sb.charAt(i) > sb.charAt(i + 1)) {                sb.deleteCharAt(i);                if (i != 0) {                    i--;                }                k--;                continue;            }            i++;        }        while (sb.length() > 1 && sb.charAt(0) == '0') sb.deleteCharAt(0);//清除头部的 0        return sb.toString();    }}
原创粉丝点击