Wednesday, May 13, 2020

LeetCode.402 Remove K Digits

1.Problem
https://leetcode.com/problems/remove-k-digits/

2.Idea
Keep deleting first x such is *xy*, x > y.

3.Source
 string removeKdigits(string num, int k) {  
      string ans = "";  
      for (int i = 0; i < num.size(); i++) {  
           while (ans.size() && ans.back() > num[i] && k) {  
                ans.pop_back();  
                k--;  
           }  
           if (ans.length() || num[i] != '0')  
                ans.push_back(num[i]);  
      }  
      while (ans.size() && k) {  
           ans.pop_back();  
           k--;  
      }  
      return ans == "" ? "0" : ans;  
 }  

No comments:

Post a Comment