182. 删除数字
作者:互联网
182. 删除数字
给出一个字符串 A, 表示一个 n 位正整数, 删除其中 k 位数字, 使得剩余的数字仍然按照原来的顺序排列产生一个新的正整数。
找到删除 k 个数字之后的最小正整数。
N <= 240, k <= N
样例
样例 1:
输入: A = "178542", k = 4
输出:"12"
样例 2:
输入: A = "568431", k = 3
输出:"431"
string DeleteDigits(string &A, int k) {
// write your code here
string tmp = A;
int count = 0;
while (count < k)
{
bool bDelete = false;
for (int first = 0; first < tmp.size(); first++)
{
bool bFind = false;
int second = first + 1;
for (; second< tmp.size(); second++)
{
if (tmp[second] <= tmp[first] && second - first <= k - count)
{
if(second - first )
bFind = true;
break;
}
}
if (true == bFind)
{
if (tmp[second] == tmp[first] )
{
if (second - first ==1)
{
continue;
}
else
{
bDelete = true;
tmp.erase((tmp.begin() + first + 1), (tmp.begin() + second));
count = count + second - first - 1;
}
}
else
{
bDelete = true;
tmp.erase((tmp.begin() + first), (tmp.begin() + second));
count = count + second - first;
}
while (tmp[0] == '0')
{
tmp = tmp.substr(1);
}
break;
}
}
if (false == bDelete)
{
tmp.erase(tmp.end() - 1);
count++;
}
}
return tmp;
}
标签:tmp,count,数字,删除,int,182,second,true,first 来源: https://blog.csdn.net/yinhua405/article/details/113676939