zoukankan      html  css  js  c++  java
  • 402. 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.
    
    class Solution {
        public String removeKdigits(String num, int k) {
            int le = num.length();
            if(k >= le || le == 0) return "0";
            while(true){
                le = num.length();
                if(le == 0) return "0";
                if(k-- == 0) return num;
                if(num.charAt(1) == '0'){
                    int zeroind = 1;
                    while(zeroind < le && num.charAt(zeroind) == '0'){
                        zeroind++;
                    }
                    num = num.substring(zeroind);
                }
                else{
                    int i = 0;
                    while(i < le-1){
                        if(num.charAt(i) > num.charAt(i+1)) 
                        {num = num.substring(0, i) + num.substring(i+1);
                        break;
                        }
                        else i++;
                    }
                    if(i == le-1) num = num.substring(0, i);
                }
            }
        }
    }

    参考 https://www.cnblogs.com/271934Liao/p/7083544.html

    有几个注意点

    1. 每次删除后num位数会减小,需要重新计算num长度

    2. 分两种情况 

      A。第二位是0,那就删掉第一位和第二位以及后面连续的0直到没0,注意这只算删了一位。如果删完了就直接返回0

      B。第二位不是0,向后检查直到发现第一个i>i+1为止,为此要设置i<length-1,注意一次只删一位,删完立刻break。如果删到最后一位还是递增,直接删除最后一位

  • 相关阅读:
    Ubuntu下的Apache、Mysql、PHP环境搭建
    JS代码引用位置问题-转
    mysql设置定时任务
    js setTimeout函数
    JavaScript向window onload添加加载函数
    写在开博之时
    WPF笔记(一)之初识XMAL
    创建理想的数据库索引
    常见负载均衡算法
    Java设计模式之外观模式
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12886149.html
Copyright © 2011-2022 走看看