leetcode 402.移掉K位数字
题干
给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。
注意:
num 的长度小于 10002 且 ≥ k。
num 不会包含任何前导零。
示例 1 :
输入: num = “1432219”, k = 3
输出: “1219”
解释: 移除掉三个数字 4, 3, 和 2 形成一个新的最小的数字 1219。
示例 2 :
输入: num = “10200”, k = 1
输出: “200”
解释: 移掉首位的 1 剩下的数字为 200. 注意输出不能有任何前导零。
示例 3 :
输入: num = “10”, k = 2
输出: “0”
解释: 从原数字移除所有的数字,剩余为空就是0。
题解
并不能过的从后向前删除
报错:
AddressSanitizer: heap-buffer-overflow on address 0x6260000090ff at pc 0x0000003adb6c bp 0x7ffd94512690 sp 0x7ffd94512688
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.length();
int targetLength = n - k;
if(n==k){
return "0";
}
int newLength = n - k;
int index = 0;
while(num.length() > targetLength && index < n && index >= 0){
if(num[index] < num[index-1]){
num = num.substr(0,index-1) + num.substr(index,n-index);
//cout<<num<<endl;
n = num.length();
index--;
}else{
index++;
}
}
if(num.length() > targetLength){
num = num.substr(0,targetLength);
}
while(num[0]=='0'){
num = num.substr(1,num.length()-1);
}
if(num.empty()){
num = "0";
}
return num;
}
};
利用栈的从前往后构造
* 用栈最后会涉及一个翻转(因为栈只能访问栈顶元素的特性),官方题解使用双向队列来避免翻转
class Solution {
public:
string removeKdigits(string num, int k) {
int n = num.length();
string finalAns = "";
stack<char> tempAns;
tempAns.push(num[0]);
for(int i=1;i<n;++i){
while(!tempAns.empty() && (int)num[i] < (int)tempAns.top() && k > 0){
tempAns.pop();
k--;
}
tempAns.push(num[i]);
}
for(int i=0;i<k;++i){
tempAns.pop();
}
if(tempAns.empty()){
return "0";
}else{
string ans;
while(!tempAns.empty()){
ans.push_back(tempAns.top());
tempAns.pop();
}
for(int i=ans.size()-1;i>=0;--i){
finalAns.push_back(ans[i]);
}
while(finalAns[0] == '0'){
finalAns = finalAns.substr(1,finalAns.size()-1);
}
if(finalAns.empty()){
return "0";
}
return finalAns;
}
}
};