-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathk digit.cpp
More file actions
29 lines (26 loc) · 769 Bytes
/
k digit.cpp
File metadata and controls
29 lines (26 loc) · 769 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
string removeKdigits(string num, int k) {
stack<char> st;
if(num.length()==k) return"0";
for(int i=0;i<num.length();i++)
{
while(!st.empty() && k>0 && st.top()>num[i])
{st.pop(); k--;}
st.push(num[i]);
}
while(k>0 &&!st.empty())
{st.pop(); k--;}
string res ="";
while(!st.empty())
{
res += st.top() ;
st.pop();}
reverse(res.begin(), res.end());
int i =0, flag=0;
while(res[i]=='0')
{i++; flag =1;}
res = flag==1?res.substr(i, res.length() -i+1):res;
return res!=""?res:"0";
}
};