Delete 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"
思路很直接,删掉K个数,需要注意的是,要按从前到后的顺序删,从前往后遍历,如果前面一个数比后面的数大,则删掉。删掉K个数。则留下的是最小的数。
由于string是不能直接操作,需要使用StringBuilder 来存储变化的string
还需要注意两点:
1、最后一个数的处理
2、如果删掉的数留下的前面是0,返回时需要从第一个不是0的数返回子串。
public class Solution { /** *@param A: A positive integer which has N digits, A is a string. *@param k: Remove k digits. *@return: A string */ public String DeleteDigits(String A, int k) { // write your code here if(A==null || A.length()==0 || k<0 || k>A.length()) return ""; StringBuilder sb=new StringBuilder(A); for(int i=0;isb.charAt(j+1)) { sb.deleteCharAt(j); break; } } } int i=0; for(;i