# Baseball Game

<https://leetcode.com/problems/baseball-game/description/>

> You're now a baseball game point recorder.
>
> Given a list of strings, each string can be one of the 4 following types:
>
> 1. `Integer`
>
>    (one round's score): Directly represents the number of points you get in this round.
> 2. `"+"`
>
>    (one round's score): Represents that the points you get in this round are the sum of the last two
>
>    `valid`
>
>    round's points.
> 3. `"D"`
>
>    (one round's score): Represents that the points you get in this round are the doubled data of the last
>
>    `valid`
>
>    round's points.
> 4. `"C"`
>
>    (an operation, which isn't a round's score): Represents the last
>
>    `valid`
>
>    round's points you get were invalid and should be removed.
>
> Each round's operation is permanent and could have an impact on the round before and the round after.
>
> You need to return the sum of the points you could get in all the rounds.

## Thoughts

要把上次或上两次存入的数拿出来，栈的一个常见应用。

## Code

```
class Solution {
    private boolean isNum(String str) {
        if (str.length() == 0) {
            return false;
        }
        if ("-0123456789".contains("" + str.charAt(0))) {
            return true;
        }
        return false;
    }

    public int calPoints(String[] ops) {
        Stack<Integer> scores = new Stack<>();
        for (String str : ops) {
            if (isNum(str)) {
                scores.push(Integer.parseInt(str));
            } else {
                switch (str) {
                    case "C":
                        if (!scores.isEmpty()) {
                            scores.pop();
                        }
                        break;
                    case "D":
                        if (!scores.isEmpty()) {
                            scores.push(scores.peek() * 2);
                        }
                        break;
                    case "+":
                        if (scores.size() >= 2) {
                            int first = scores.pop();
                            int sec = scores.pop();
                            scores.push(sec);
                            scores.push(first);
                            scores.push(first + sec);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        int res = 0;
        for (Integer num : scores) {
            res += num;
        }

        return res;
    }
}
```

## Analysis

做题耗时15min

时空复杂度O(n).
