402. Remove K Digits

(English version is after the code part)

这个题做起来比看起来容易,然后我也没仔细想,先速度刷完,以后再看有没有改进。
用这个来说:

1 2 4 3 2 2 1 9
去掉1位的话,应该去掉4,得到 1 2 3 2 2 1 9
去掉2位的话,在刚才的基础上,去掉3,得到1 2 2 2 1 9.

显而易见,每次找第一个最大值。上面的例子,第一次找到的是4,第二次是3,下一个数开始变小就不找了,所以找不到最后的9.

然后就各种特殊情况。

首先例子已经给了一个提示: "10200", k = 1
第一位之后如果是0,就要去掉第一位和后面所有的0)。

还有特殊情况,比如相等: "122211" "122231"
前者在相等之后,出现一个小的 1,所以去掉相等的其中一个。
后者在相等之后,出现一个大的 3,所以去掉3.

可以在出现等于的时候就记住第一个相等元素的index,以便最后出现一个小的,直接去掉INDEX的元素就行了。
也可以不用记,因为最终搜索停止前者停在最后1个2,后者停在3,正好是要去掉的元素。但是这里牵扯一个问题,就是搜索到底,12222或者12345这样的情况,要去掉最后一个。

剩下的就是一步能判断的情况,比如k = num.length, 最后是空字符就返还0之类的。

代码就按部就班写的,AC之后再没管,过两天数据多了再改进,求不喷。

public class Solution {
    public String removeKdigits(String num, int k) 
    {
         if(k == 0 || num.length() == 0) return num;
         if(k == num.length()) return "0";
         
         for(int i = 0; i < k;i++)
         {
             int j = 0;
             if(j+1 < num.length() && num.charAt(j+1) == '0')  num = num.substring(2);
             else
             {
                boolean finish = false;
                j = 0;
                while(j+1 < num.length())
                {
                    if(num.charAt(j) <= num.charAt(j+1)) j++;
                    else
                    {
                        finish = true;
                        num = num.substring(0,j) + num.substring(j+1);
                        break;
                    }
                }
                     
                if(!finish) num = num.substring(0,num.length()-1);
             }
             
            
            
            int z = 0; 
            while(z < num.length() && num.charAt(z) == '0') z++;
            num = num.substring(z);
    
         }
         if(num.length() == 0) return "0";
         return num;
    }
    

}

See this eg below:
1 2 4 3 2 2 1 9
When k = 1, meaning get rid of 1 digit, then we shall remove element 4, and get a result
1 2 3 2 2 1 9
When k = 2,based on previous step, we remove 3, and get
1 2 2 2 1 9

The rule is every time we wanna remove an element, we search from index 0, find the first local max value. And that's it.

The rest are just edge cases. Examples in description alredy provided 2 for us.

When the first digit is following by several 0s, we shall remove the first digit and all the following 0s.

num.length == k, return "0"

When searching for a local max value, we move on if 2 neighbor elements are the same, and decide later.

If an empty string left, return "0".

Just an acceptable version.

转载于:https://www.cnblogs.com/reboot329/p/5883739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值