给定一个以字符串表示的非负整数 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-k-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
string removeKdigits(string num, int k) {
vector<char> ans;
for (auto & digit: num) {
while(ans.size() > 0 && ans.back() > digit && k) {
ans.pop_back();
k -= 1;
}
ans.push_back(digit);
}
for (; k > 0; k--) {
ans.pop_back();
}
string res = "";
bool isLeadingZero = true;
for (auto & digit: ans) {
if (isLeadingZero && digit == '0') {
continue;
}
isLeadingZero = false;
res += digit;
}
return res == "" ? "0" : res;
}
};
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
ans = []
for digit in num:
while k and ans and ans[-1] > digit:
ans.pop()
k -= 1
ans.append(digit)
res = ans[:-k] if k else ans
return "".join(res).lstrip('0') or "0"
char * removeKdigits(char * num, int k){
int n = strlen(num);
int top = 0;
char *ans = malloc(sizeof(char) * (n + 1));
for (int i = 0; i < n; i++) {
while (top > 0 && ans[top] > num[i] && k) {
top--;
k--;
}
ans[++top] = num[i];
}
top -= k;
char *res = malloc(sizeof(char) * (n + 1));
int resSize = 0;
bool isLeadingZero = true;
for (int i = 1; i < top + 1; i++) {
if (isLeadingZero && ans[i] == '0') {
continue;
}
isLeadingZero = false;
res[resSize++] = ans[i];
}
if (resSize == 0) {
res[0] = '0';
res[1] = '\0';
}
else {
res[resSize] = '\0';
}
return res;
}