c语言sscanf函数的用法是什么
272
2022-08-29
LeetCode-402. Remove K Digits
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 ofnumis less than 10002 and will be ≥k.The givennumdoes not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3Output: "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 = 1Output: "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 = 2Output: "0"Explanation: Remove all the digits from the number and it is left with nothing which is 0.
题解:想了很久吧这题,之前用vector但是超时,后来发现string类也有push_back,back,pop_back之类的函数= =
class Solution {public: string removeKdigits(string num, int k) { int len = num.length(), n = len - k; if (n == 0) { return "0"; } if (n >= len) { return num; } string res; for (int i = 0; i < len; i++) { while(k > 0 && res.length() > 0 && res.back() > num[i]) { res.pop_back(); k--; } res += num[i]; } res = res.substr(0, n); while (res[0] == '0') { res.erase(0, 1); } if (res.length() == 0) { return "0"; } return res; }};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~