Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- static size_t toNum(char c) {
- return c - '0';
- }
- public:
- string removeKdigits(string num, int k) {
- std::stack<char> st;
- for(const char& c : num) {
- while(k > 0 && !st.empty() && toNum(st.top()) > toNum(c)) {
- st.pop();
- --k;
- }
- st.push(c);
- }
- while(!st.empty() && k) {
- st.pop();
- --k;
- }
- std::string result;
- result.resize(st.size());
- size_t idx = st.size() - 1;
- while(!st.empty()) {
- char c = st.top();
- st.pop();
- result[idx--] = c;
- }
- idx = 0;
- while(idx < result.size() - 1 && result[idx] == '0') {++idx;}
- result = std::string(result.begin() + idx, result.end());
- return result == "" ? "0" : result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement