1: class Solution { 2: public: 3: string removeKdigits(string num, int k) { 4: string res = ""; 5: int n = num.size(), sz = n-k; 6: for (c : num) { 7: while (k && !res.empty() && res.back() > c) { 8: res.pop_back(); 9: k--; 10: } 11: res += c; 12: } 13:
res.resize(sz);
14: int i = 0; 15: while (!res.empty() && res[i] == '0') i++; 16: res = res.substr(i); 17: return res.empty() ? "0" : res; 18: } 19: };
Sunday, October 9, 2016
402. Remove K Digits
I was thinking the K digits must be consecutive but it turns out it's not necessary. So the problem becomes easier. All I need to do is to discard the number that is larger than current number. Line 13 is very trick. Without this line, the code fails the case of ["9", 1]
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment