我才用的是往队列加需要的字母
public class Solution {
public String removeKdigits(String num, int k) {
Queue<Character> queue = new LinkedList<>();
int len = num.length();
int nowLen = len - k;//这是个区间长度,比如num="102",k=1开始区间长度为2,因为1,和0可以选,但当加入一位到队列中后,区间长度就变为1(每次减一),因为只有以为可以选,
int count = 0;//加入字母的数量
int start = 0;//每次选数开始的地方
while (count < len - k&&start<len) {
int index = start;
int min = num.charAt(start);
//再选的区间里选最小的数,还要把位置纪录下来
for (int i = start+1; i <=len- nowLen; i++) {
if (num.charAt(i) < min) {
index = i;
min = num.charAt(i);
}
}
queue.offer(num.charAt(index));//选中后加入队列
count ++;
start=index+1;//下次的开始位置
nowLen--;
}
StringBuffer stringBuffer = new StringBuffer();
if (queue.isEmpty())return "0";
int flag=0;
//来处理像“”0003210"这样开头是0的数
while (!queue.isEmpty()){
if (flag==0&&queue.peek()=='0'){
queue.poll();
}else if (flag==0&&queue.peek()!='0'){
stringBuffer.append(queue.poll());
flag=1;
}else{
stringBuffer.append(queue.poll());
}
}
if(stringBuffer.toString().equals(""))return "0";
return stringBuffer.toString();
}
}
我还看到了一个往栈里加字母(通过删除法)的方法,好像是标答,方法挺好的
public class Solution {
public String removeKdigits(String num, int k) {
int len = num.length();
//corner case
if(k==len)
return "0";
Stack<Character> stack = new Stack<>();
int i =0;
while(i<num.length()){
//whenever meet a digit which is less than the previous digit, discard the previous one
//只要不超过删除k的数量,只要有当前的数比栈中的数小,就把栈的数删了,放它进入。删了的数就算被永久的删了,不再考虑了
while(k>0 && !stack.isEmpty() && stack.peek()>num.charAt(i)){
stack.pop();
k--;
}
stack.push(num.charAt(i));
i++;
}
// corner case like "1111"
while(k>0){
stack.pop();
k--;
}
//construct the number from the stack
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty())
sb.append(stack.pop());
sb.reverse();
//remove all the 0 at the head
while(sb.length()>1 && sb.charAt(0)=='0')
sb.deleteCharAt(0);
return sb.toString();
}
}