**2390. 从字符串中移除星号(栈入门)**

Untitled

public String removeStars(String s) {
    Deque stack = new ArrayDeque();
    // 采用栈依次存放字符串,如果是*弹出栈来
    for(char star: s.toCharArray()) {
        if(c == '*' && !stack.isEmpty()) {
            stack.removeFirst();
        }else {
            stack.addFirst(c);
        }
    }
    // 破坏栈结构,依次用栈底取值
    StringBuilder sb = new StringBuilder();
    while(!stack.isEmpty()) {
        sb.append(stack.peekLast());
        stack.removeLast();
    }
    return sb.toString();
}

**735. 行星碰撞(栈的应用)**

Untitled

public int[] asteroidCollision(int[] asteroids) {
    Deque<Integer> stack = new ArrayDeque<>();
    for(int star: asteroids) {
        if(star > 0) {
            stack.addFirst(star);
        }else {
            boolean explosion = false;
            while(!stack.isEmpty()) {
                if(stack.peekFirst() > 0) {
                    if(stack.peekFirst() < -1 * star) {
                        stack.removeFirst();
                        continue;
                    }else if(stack.peekFirst() == -1 * star) {
                        stack.removeFirst();
                        explosion = true;
                        break;
                    }else {
                        explosion = true;
                        break;    
                    }
                }else {
                    stack.addFirst(star);
                    explosion = true;
                    break;
                }
            }
            if(explosion == false) {
                stack.addFirst(star);
            }
        }
    }
    // 打印最后数组
    int size = stack.size();
    int[] ans = new int[size];
    while(!stack.isEmpty()) {
        ans[stack.size() - 1] = stack.removeFirst();
    }
    return ans;
}

**394. 字符串解码(比较难的栈的应用)**

Untitled

public String decodeString(String s) {
    StringBuilder sb = new StringBuilder();
    int n = s.length();
    char[] chars = s.toCharArray();
    Deque<Character> deque = new ArrayDeque<>();

    for(int i = 0; i < n; i++) {
        // 正常字母直接添加在列表中
        if('a' <= chars[i] && chars[i] <= 'z') {
            sb.append(chars[i]);
            continue;
        }
        // 否则先统计次数,再添加多次到列表中
        int count = 0;
        int left = 0;
        while('0' <= chars[i] && chars[i] <= '9') {
            count *= 10;
            count += chars[i] - '0';
            i++;
        }
        i++;
        
        // 找到括号中的字符串,然后递归构造子字符
        int left_point = i;
        left++;
        while(left != 0) {
            if(chars[i] == ']') left--;
            else if(chars[i] == '[') left++;
            i++;
        }

        String inner = decodeString(s.substring(left_point, i-1));
        // 添加多次字符串
        for(int j = 0; j < count; j++) 
            sb.append(inner);
        i--;
    }
    return sb.toString();
}