Advertisement
Stoycho_KK

Untitled

Oct 19th, 2022
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. class Solution {
  2. static size_t toNum(char c) {
  3.     return c - '0';
  4. }
  5. public:
  6.     string removeKdigits(string num, int k) {
  7.     std::stack<char> st;
  8.        
  9.     for(const char& c : num) {
  10.         while(k > 0 &&  !st.empty() && toNum(st.top()) > toNum(c)) {
  11.             st.pop();
  12.             --k;
  13.         }
  14.        
  15.         st.push(c);
  16.     }
  17.  
  18.    while(!st.empty() && k) {
  19.       st.pop();
  20.       --k;
  21.    }
  22.        
  23.     std::string result;
  24.     result.resize(st.size());
  25.     size_t idx = st.size() - 1;
  26.    
  27.    while(!st.empty()) {
  28.       char c = st.top();
  29.        st.pop();
  30.        result[idx--] = c;
  31.    }
  32.    idx = 0;
  33.    while(idx < result.size() - 1 && result[idx] == '0') {++idx;}
  34.        
  35.    result = std::string(result.begin() + idx, result.end());
  36.        
  37.    
  38.    return result == "" ? "0" : result;
  39. }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement