思路:对于一个数字,删除任何一位都会使其使其下降一个等级,那么应该删除哪一位呢?对1243而言,显然应该删掉‘4’;10200应该删掉'1', 1421应该删掉‘4’;1234应该删掉'4‘;综上,可以用一个栈维持一个递增序列,当压入栈的元素比栈顶元素小时,把栈顶元素弹出。
代码:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#include <time.h>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define lson l,mid,rt<<1
#define rson mid,r,rt<<1|1
#define lrt rt << 1
#define rrt rt << 1|1
#define root 1,n,1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const LL INF = (((LL)1)<<62)+1;
using namespace std;
const double eps = 1e-5;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const double M=1e-8;
const int N=1100;
typedef pair<int, int> pii;
typedef pair<double,double> pdd;
typedef pair<int, string> pis;
const int d[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
class Solution {
public:
string removeKdigits(string num, int k) {
if (num.length() == k) {
string ans = "0";
return ans;
}
char st[N];
int top=0, bottom = 0;
st[top++] = num[0];
int i=1;
while(k && i < num.length()) {
while (k && top>0 && st[top - 1] > num[i]) { // 循环弹出比num[i]小的栈顶元素
top -- ;
k--;
}
st[top++] = num[i];
i++;
}
while (i < num.length()) st[top++] = num[i++];
while(k && top>0) top--,k--; // 处理 输入为11111,2 和 1234562的情况
st[top] = '\0';
char *p = st;
while(*p == '0') p++;
string ans = p;
return ans==""?"0":ans;
}
};
int main()
{
char a[N] = "a";
char *p = a;
p++;
string str = p;
cout<<"str:"<<(str==""?1:0)<<endl;
Solution s;
cout<<s.removeKdigits("1432219", 3)<<endl;
cout<<s.removeKdigits("10200", 1)<<endl;
cout<<s.removeKdigits("10200", 2)<<endl;
cout<<s.removeKdigits("111111", 2)<<endl;
cout<<s.removeKdigits("1234567890", 9)<<endl;
cout<<s.removeKdigits("123456789", 8)<<endl;
cout<<s.removeKdigits("10", 1)<<endl;
}