sunfresh

Baseball Game

Jan 17th, 2023
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. Baseball Game
  2. You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
  3.  
  4. You are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:
  5.  
  6. An integer x.
  7. Record a new score of x.
  8. '+'.
  9. Record a new score that is the sum of the previous two scores.
  10. 'D'.
  11. Record a new score that is the double of the previous score.
  12. 'C'.
  13. Invalidate the previous score, removing it from the record.
  14. Return the sum of all the scores on the record after applying all the operations.
  15.  
  16. The test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
  17.  
  18. class Solution {
  19. public int calPoints(String[] operations) {
  20. Stack<Integer> stack = new Stack<>();
  21.  
  22. for (String s : operations) {
  23. if (s.equals("+")) {
  24. int a = stack.pop();
  25. int newScore = a + stack.peek();
  26. stack.push(a);
  27. stack.push(newScore);
  28. }
  29. else if (s.equals("D")) {
  30. stack.push(2 * stack.peek());
  31. }
  32. else if (s.equals("C")) {
  33. stack.pop();
  34. }
  35. else stack.push(Integer.parseInt(s));
  36. }
  37.  
  38. int totalScore = 0;
  39. while (!stack.isEmpty()) totalScore += stack.pop();
  40.  
  41. return totalScore;
  42. }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment