---
# System prepended metadata

title: 0402. Remove K Digits
tags: [Leetcode, Medium, Stack]

---

# 0402. Remove K Digits
###### tags: `Leetcode` `Medium` `Stack`
Link: https://leetcode.com/problems/remove-k-digits/
## 思路
遍历字符串 当出现前一位大于后一位的时候 然后k大于0 就把前一位删掉
需要注意corner case 可能出现 遍历完字符串 k还没用完的情况 比如"1234"，本来就是排好的
还要注意heading zero
## Code
```java=
class Solution {
    public String removeKdigits(String num, int k) {
        Stack<Character> stack = new Stack<>();
        for(int i=0; i<num.length(); i++){
            while(k>0 && !stack.isEmpty() && stack.peek()>num.charAt(i)){
                stack.pop();
                k--;
            }
            stack.add(num.charAt(i));
        }
        
        // corner case like "1111"
        while(k>0){
            k--;
            stack.pop();
        }
        
        //construct the number
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        sb.reverse();
        
        //remove heading zero
        while(sb.length()>=1 && sb.charAt(0)=='0'){
            sb.deleteCharAt(0);
        }
        return sb.length()==0?"0":sb.toString();
    }
}
```