Simple Java Code ☠️
\n\n# Code\n\nclass Solution {\n    public int calPoints(String[] operations) {\n        int n = operations.length;\n        Stack<Integer> stack = new Stack<>(
\n\n# Code\n```\nclass Solution {\n    public int calPoints(String[] operations) {\n        int n = operations.length;\n        Stack<Integer> stack = new Stack<>();\n        for(int i=0;i<n;i++){\n            String str = operations[i];\n            char ch = str.charAt(0);\n            if(Character.isDigit(ch)  || ch==\'-\'){\n                stack.push(Integer.parseInt(str));\n            }\n            else if(!stack.isEmpty()){\n                if(ch == \'+\' && stack.size()>1){\n                    int a = stack.pop();\n                    int b = stack.peek();\n                    stack.push(a);\n                    stack.push(a+b);\n                }\n                else if(ch == \'D\'){\n                    int a = stack.peek();\n                    stack.push(a*2);\n                }\n                else if(ch==\'C\'){\n                    stack.pop();\n                }\n            }\n        }\n        int sum=0;\n        while(!stack.isEmpty()){\n            sum+=stack.pop();\n        }\n        return sum;\n    }\n}\n```\n\n\n\n### Problem Recap\nYou are given a list of operations for a baseball game, where:\n1. An integer x represents recording a new score x.\n2. The operation \'+\' means recording a new score that is the sum of the previous two scores.\n3. The operation \'D\' means recording a new score that is the double of the previous score.\n4. The operation \'C\' means invalidating the previous score, removing it from the record.\n\nThe goal is to calculate the sum of all valid scores after performing all operations.\n\n### Detailed Code Explanation:\n\n#### Initialization:\n```java\nint n = operations.length;\nStack<Integer> stack = new Stack<>();\n```\n- `int n = operations.length;` - This gets the number of operations.\n- `Stack<Integer> stack = new Stack<>();` - We use a stack to keep track of the scores. The stack allows us to easily manage the most recent scores, which is useful for operations like \'+\', \'D\', and \'C\'.\n\n#### Processing Each Operation:\nWe iterate through each operation in the list:\n```java\nfor(int i = 0; i < n; i++){\n    String str = operations[i];\n    char ch = str.charAt(0);\n```\n- `for(int i = 0; i < n; i++) { ... }` - Loop through each operation.\n- `String str = operations[i];` - Get the current operation as a string.\n- `char ch = str.charAt(0);` - Get the first character of the string to determine the type of operation.\n\n#### Handling Number Operations:\n```java\nif (Character.isDigit(ch) || ch == \'-\') {\n    stack.push(Integer.parseInt(str));\n}\n```\n- `Character.isDigit(ch)` - Checks if the first character is a digit.\n- `ch == \'-\'` - Checks if the first character is a minus sign, indicating a negative number.\n- `stack.push(Integer.parseInt(str));` - Converts the string to an integer and pushes it onto the stack.\n\n#### Handling Special Operations:\n```java\nelse if (!stack.isEmpty()) {\n    if (ch == \'+\' && stack.size() > 1) {\n        int a = stack.pop();\n        int b = stack.peek();\n        stack.push(a);\n        stack.push(a + b);\n    } else if (ch == \'D\') {\n        int a = stack.peek();\n        stack.push(a * 2);\n    } else if (ch == \'C\') {\n        stack.pop();\n    }\n}\n```\n- `else if (!stack.isEmpty()) { ... }` - Ensures the stack is not empty before performing operations that require existing scores.\n  \n1. **Sum Operation (\'+\'):**\n   ```java\n   if (ch == \'+\' && stack.size() > 1) {\n       int a = stack.pop();\n       int b = stack.peek();\n       stack.push(a);\n       stack.push(a + b);\n   }\n   ```\n   - `stack.size() > 1` - Ensures there are at least two scores to sum.\n   - `int a = stack.pop();` - Temporarily removes the top score.\n   - `int b = stack.peek();` - Gets the next top score without removing it.\n   - `stack.push(a);` - Pushes the removed score back onto the stack.\n   - `stack.push(a + b);` - Pushes the sum of the last two scores onto the stack.\n\n2. **Double Operation (\'D\'):**\n   ```java\n   else if (ch == \'D\') {\n       int a = stack.peek();\n       stack.push(a * 2);\n   }\n   ```\n   - `int a = stack.peek();` - Gets the top score without removing it.\n   - `stack.push(a * 2);` - Pushes the double of the top score onto the stack.\n\n3. **Cancel Operation (\'C\'):**\n   ```java\n   else if (ch == \'C\') {\n       stack.pop();\n   }\n   ```\n   - `stack.pop();` - Removes the top score from the stack, invalidating it.\n\n#### Calculating the Final Sum:\n```java\nint sum = 0;\nwhile (!stack.isEmpty()) {\n    sum += stack.pop();\n}\nreturn sum;\n```\n- `int sum = 0;` - Initializes the sum to 0.\n- `while (!stack.isEmpty()) { sum += stack.pop(); }` - Pops each score from the stack and adds it to the sum until the stack is empty.\n- `return sum;` - Returns the final sum of all valid scores.\n\n\n### Example Walkthrough\n\nLet\'s consider an example to illustrate how the code works. Suppose we have the following operations:\n\n```java\nString[] operations = {"5", "-2", "4", "C", "D", "9", "+", "+"};\n```\n\nLet\'s go through each operation step-by-step:\n\n1. **"5"**: \n    - This is a number, so we push it onto the stack.\n    - Stack: `[5]`\n\n2. **"-2"**: \n    - This is a number, so we push it onto the stack.\n    - Stack: `[5, -2]`\n\n3. **"4"**: \n    - This is a number, so we push it onto the stack.\n    - Stack: `[5, -2, 4]`\n\n4. **"C"**:\n    - This operation invalidates the previous score, so we pop the top of the stack.\n    - Stack: `[5, -2]`\n\n5. **"D"**:\n    - This operation records a new score that is double the previous score.\n    - Previous score: `-2`\n    - New score: `-4`\n    - Stack: `[5, -2, -4]`\n\n6. **"9"**:\n    - This is a number, so we push it onto the stack.\n    - Stack: `[5, -2, -4, 9]`\n\n7. **"+"**:\n    - This operation records a new score that is the sum of the previous two scores.\n    - Previous two scores: `-4` and `9`\n    - New score: `5`\n    - Stack: `[5, -2, -4, 9, 5]`\n\n8. **"+"**:\n    - This operation records a new score that is the sum of the previous two scores.\n    - Previous two scores: `9` and `5`\n    - New score: `14`\n    - Stack: `[5, -2, -4, 9, 5, 14]`\n\nFinally, we sum all the scores in the stack:\n\n```\n5 + (-2) + (-4) + 9 + 5 + 14 = 27\n```\n\nSo the function returns `27`.\n\n### Time Complexity : \\[ O(n) \\]\n\n### Space Complexity : \\[ O(n) \\]\n\n\n
['Array', 'Stack', 'Simulation', 'Java']