题目:
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.分析(Stack实现):
class Solution {
public String removeKdigits(String num, int k) {
//给定一个用字符串代表队数,移除其中k个元素 。返回其最小的值。
//要求:长度少于10002,k的长度小于活着等于字符串长度。
//思路:使用stack存储最小的,直到满足去除了k个元素后,就停止类比寻找更小的。
//暴力解法:LTM,数组长度太长
int len=num.length();
if(k==len) return "0";
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<len;i++){
//类比,查找比栈定更小的元素
while(k>0&&!stack.empty()&&stack.peek()>num.charAt(i)){
//栈顶大的元素出栈
stack.pop();
k--;
}
//进栈
stack.push(num.charAt(i));
}
//防止:11111和12345情况
while(k>0){
stack.pop();
k--;
}
//对stack中的元素进行输出,因为stack存储的是最小的,所以0在最下面
StringBuilder sb=new StringBuilder();
while(!stack.empty()){
sb.append(stack.pop());
}
//为了将逆转后的0剔出
while(sb.length()>1&&sb.charAt(sb.length()-1)=='0'){
sb.deleteCharAt(sb.length()-1);
}
//逆序输出结果
return sb.reverse().toString();
}
}
分析2(数组-参考答案):
class Solution {
public String removeKdigits(String num, int k) {
//给定一个用字符串代表队数,移除其中k个元素 。返回其最小的值。
//要求:长度少于10002,k的长度小于活着等于字符串长度。
//思路:使用数组实现,类似stack的实现
//暴力解法:LTM,数组长度太长
int len=num.length();
if(k==len) return "0";
if(k==0) return num;
char [] chs=num.toCharArray();
//移动栈顶游标
int index=-1;
for(int i=0;i<len;i++){
//类比查找栈顶比其小
while(k>0&&index!=-1&&chs[index]>chs[i]){
index--;
k--;
}
//赋值
chs[++index]=chs[i];
}
//防止特殊情况:12345或者11111
while(k>0){
index--;
k--;
}
//查找最前面的0
int zero=0;
while(chs[zero]=='0'&&zero<index){
zero++;
}
//输出结果,截取特定长度
String res=new String(chs,zero,index-zero+1);
return res;
}
}