LeetCode402. Remove K Digits
原题地址
题目描述
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.
思路
从原数字的高位到低位检索,删除第一个下降的数字,然后又从头开始检索,依次删除K次,因为每删除一次数量级固定下降一位,所以如果是后一位比这一位大,删除这一位那么后一位更大的数就会在比较高的数量级上,但如果后一位更小的话,就会让小的数到高位上来。所以按照这个规律,最后在注意一下去掉开头的0,就可以得到结果。
代码实现
class Solution {
public:
string remove(string & num, int pos) {
return num.substr(0, pos) + num.substr(pos+1, num.size()-pos-1);
}
string removeKdigits(string num, int k) {
if(num.size()<=k) return "0";
for(int i=0; i<k; i++){
for(int j=0; j<num.size(); j++){
if(j==num.size()-1 || num[j]>num[j+1]){
num=remove(num,j);
break;
}
}
}
while(num[0]=='0') num=remove(num,0);
if (num.size() == 0) return "0";//num="10",k=1的情况
return num;
}
};
ps: substr()函数
basic_string substr(size_type _Off = 0,size_type _Count = npos) const;
参数
_Off
所需的子字符串的起始位置。字符串中第一个字符的索引为 0,默认值为0.
_Count
复制的字符数目